LoginSignup
2
3

More than 5 years have passed since last update.

next_link_post(もしくはprevious_link_post)で表示されるリンクを子カテゴリにする

Posted at

やりたいこと

カテゴリの配置が

 - 親カテゴリ
    - 子カテゴリ1
        - 記事A
        - 記事B
        - 記事C
    - 子カテゴリ2
        - 記事D
        - 記事E
        - 記事F

    - 子カテゴリ3
        - 記事G
        - 記事H
        - 記事I

であるときに、next_link_postprevious_link_postを使用したとき(同じカテゴリ内で探すことを有効にした場合)、

記事Cのときには、記事Bだけが表示されて欲しいが、記事Bと記事Dが表示されてしまう。

これを子カテゴリ内だけ(記事Bを表示したら、記事Aと記事Cが出て欲しいよう)にしたい。

やったこと

特定のカテゴリを除く処理があるのでそれを使って、同じ親カテゴリを持っている子カテゴリを取得して、現在の記事の子カテゴリではないカテゴリを取り除くようにした。

コード

これをfunction.phpに置いて必要な場合は適宜呼び出している。

function.php

function exclude_different_child_category_posts() {
  $same_parent_category_ids = array();
  $current_categories = get_the_category();
  foreach($current_categories as $category){
    $args = array('parent'  => $category->term_id);
    $cate_children = get_categories($args);
    foreach($cate_children as $cate_child){
      array_push($same_parent_category_ids, $cate_child->term_id);
    }
  }

  //重複を避ける
  $same_parent_category_ids = array_unique($same_parent_category_ids);

  $current_category_ids = array_map(function($v){ return $v->term_id; }, $current_categories);

  $excluded_category_ids = array_diff($same_parent_category_ids, $current_category_ids);

  return $excluded_category_ids;
}

使うときは呼び出す。


<?php

$exclude_category_ids = exclude_different_child_category_posts();

?>


<?php previous_post_link('%link', '&laquo; %title', true, $excluded_category_ids) ?>


参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3