ASITIS

ブログ用のメモブログ

WordPressのカテゴリーを投稿順に並べる

カテゴリーを投稿の新しい順に並べたかったので、少し無理矢理感もありますが元々ある配列array_multisort();でソートし直す。

希望どうりには動いてます。

※カスタム分類、カスタム投稿にも対応

function new_taxonomy_array($taxonomy = 'category') {
  $taxs = get_terms($taxonomy,
    array(
      'orderby'           => 'name',
      'order'             => 'ASC',
      'hide_empty'        => false,
      'exclude'           => array(1),
      'exclude_tree'      => array(),
      'include'           => array(),
      'number'            => '',
      'fields'            => 'all',
      'slug'              => '',
      'parent'            => '',
      'hierarchical'      => true,
      'child_of'          => 0,
      'childless'         => false,
      'get'               => '',
      'name__like'        => '',
      'description__like' => '',
      'pad_counts'        => false,
      'offset'            => '',
      'search'            => '',
      'cache_domain'      => 'core'
      )
    );
  $new_array = array();
  if(!is_wp_error($taxs) && count($taxs)):
    foreach($taxs as $tax):
      $taxPosts = get_posts(
        array(
          'posts_per_page'   => -1,
          'offset'           => 0,
          'category'         => '',
          'category_name'    => '',
          'tax_query'        => array(
            array (
              'taxonomy' => $taxonomy,
              'field'    => 'slug',
              'terms'    => $tax->slug
              )
            ),
          'orderby'          => 'post_date',
          'order'            => 'DESC',
          'include'          => '',
          'exclude'          => '',
          'meta_key'         => '',
          'meta_value'       => '',
          'post_type'        => 'post',
          'post_mime_type'   => '',
          'post_parent'      => '',
          'author'           => '',
          'post_status'      => 'publish',
          'suppress_filters' => true
          )
        );

      if($taxPosts):
        $new_array[] = array(
            'update'=> (isset($taxPosts[0]->post_date)? $taxPosts[0]->post_date: '0'),
            'title' => $tax->name,
            'link'  => get_category_link($tax->term_id),
            'id'    => $tax->term_id,
            'count' => count($taxPosts)
          );
        // ソートしなおし
        foreach ((array)$new_array as $key => $value) {
          $sort[$key] = $value['update'];
        }
        array_multisort($sort, SORT_DESC, $new_array);
      endif;
    endforeach; wp_reset_postdata();
  endif;

  return $new_array;
}

出力方法

$_tax_array = new_taxonomy_array('category');
if($_tax_array):
  foreach((array)$_tax_array as $key => $value){
    echo $value['update'];
    echo $value['title'];
    echo $value['link'];
    echo $value['id'];
    echo $value['count'];
  endforeach;
endif;