WordPress 特定のカスタムフィールドに値がある記事だけで「前へ」「次へ」を実装

「このカスタムフィールドに値がある記事だけで『前の記事へ』『次の記事へ』のページ送りを実装してください」と言われたけど、思ったより大変だったのでメモ。

通常、詳細記事のページネーションは”previous_post_link()”と”next_post_link()”を使えば簡単に実装できるんだけど、この関数は残念ながらカスタムフィールドの有無の判定とかはできないので、がんばってphpを書いたのであった。




functions.phpに以下を記述

function get_custom_pagenation() {
  global $post;
  $html = '';
  $current_id = $post->ID; //現在の記事のID
  $array_has_thumb = array();

  // カスタムフィールドに値がある記事を全部出して、"$array_has_thumb"にIDを格納
  $wp_query = new WP_Query();
  $param = array(
    'posts_per_page' => '-1',
    'post_type' => 'post',
    'meta_key' => 'hoge',
    'meta_value' => false,
    'meta_compare' => '!='
  );
  $wp_query -> query( $param );

  if( $wp_query -> have_posts() ){
    while( $wp_query -> have_posts() ) {
      $wp_query -> the_post();
      $array_has_thumb[] = $post->ID;
    }
  }
  wp_reset_query();

  // "$array_has_thumb"から現在の記事IDのキーを取り出しておく
  $current_key = array_keys( $array_has_thumb, $current_id );

  // 前の記事のID
  foreach( $array_has_thumb as $data ) {
    if( $data == $current_id ) {
      break;
    }
    $prev_id = $data;
  }
  // 次の記事のID
  foreach( $array_has_thumb as $key => $value ) {
    $next_id = $value;

    if( $key > $current_key[0] ) {
      break;
    }
  }
  if( $next_id == $data ) {
    $next_id = NULL;
  }

  // IDが取得出来たらその記事のパーマリンクを取得
  if ( $prev_id ) {
    $prev_link = get_permalink( $prev_id );
  }
  if ( $next_id ) {
    $next_link = get_permalink( $next_id );
  }

  // 出力部分
  if( $prev_link ) {
    $html .= '<p class="prev"><a href="' .$prev_link. '">前の記事へ</a></p>';
  }
  $html .= '<p class="list"><a href="' .home_url('/'). '">トップへ</a></p>';
  if ( $next_link ) {
    $html .= '<p class="next"><a href="' .$next_link. '">次の記事へ</a></p>';
  }
  return $html;
}

だいたいコメントに書いてある通りの処理です。

要は、

  • まず’hoge’というカスタムフィールドに値がある記事のみループさせ、
  • 配列’$array_has_thumb’に記事IDを格納。
  • その配列から、今の記事IDの前後の記事IDを取得して、
  • 記事IDが取得できていたらページネーションを表示

という流れです。前後の記事IDを取得する部分はもうちょい綺麗に書けそう…あとは、meta_keyやpost_typeの値を引数で渡してやると汎用性高まりますね。まぁそれは気が向いたら挑戦してみてください。🤗

 

使うときはテンプレートに

<?php echo get_custom_pagenation(); ?>

と書くと表示されます。

 

現場からは以上です。

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です