KANTENNA.COM

Solarized

HOME > WEBプログラム覚書 > [WordPress] 次の投稿と前の投稿を取得する。

[WordPress] 次の投稿と前の投稿を取得する。

次の投稿とか前の投稿を取得するget_adjacent_post()が、どうもループ内じゃないと利用できないようになっている模様。

get_adjacent_post()はループの際に作成されるグローバル変数の$postを使うようになっているので、 どの投稿を使うかこちらで決めれるようにちょっとだけ変更してみる。

functions.php
  1.  <?php
  2.   /**
  3.   * グローバルの$postを利用しないようにする
  4.   *
  5.   *
  6.   * Retrieve adjacent post.
  7.   *
  8.   * Can either be next or previous post.
  9.   *
  10.   * @since 2.5.0
  11.   * @see get_adjacent_post()
  12.   *
  13.   * @param int|object 投稿IDか投稿オブジェクト
  14.   * @param bool $in_same_cat Optional. Whether post should be in a same category.
  15.   * @param array|string $excluded_categories Optional. Array or comma-separated list of excluded category IDs.
  16.   * @param bool $previous Optional. Whether to retrieve previous post.
  17.   * @return mixed Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
  18.   */
  19.   function my_get_adjacent_post($postdata = null, $in_same_cat = false, $excluded_categories = '', $previous = true ) {
  20.   global $wpdb;
  21.  
  22.   if (is_null($postdata)) {
  23.   global $post;
  24.   } else {
  25.   if (is_numeric($postdata)) {
  26.   $post = get_post($postdata = (int) $postdata, OBJECT);
  27.   } elseif ($postdata instanceof stdClass && is_propety('post_type', $postdata) && $postdata->post_type === 'post') {
  28.   $post = $postdata;
  29.   }
  30.   }
  31.  
  32.   if ( empty( $post ) )
  33.   return null;
  34.  
  35.   $current_post_date = $post->post_date;
  36.  
  37.   $join = '';
  38.   $posts_in_ex_cats_sql = '';
  39.   if ( $in_same_cat || ! empty( $excluded_categories ) ) {
  40.   $join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
  41.  
  42.   if ( $in_same_cat ) {
  43.   $cat_array = wp_get_object_terms($post->ID, 'category', array('fields' => 'ids'));
  44.   $join .= " AND tt.taxonomy = 'category' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
  45.   }
  46.  
  47.   $posts_in_ex_cats_sql = "AND tt.taxonomy = 'category'";
  48.   if ( ! empty( $excluded_categories ) ) {
  49.   if ( ! is_array( $excluded_categories ) ) {
  50.   // back-compat, $excluded_categories used to be IDs separated by " and "
  51.   if ( strpos( $excluded_categories, ' and ' ) !== false ) {
  52.   _deprecated_argument( __FUNCTION__, '3.3', sprintf( __( 'Use commas instead of %s to separate excluded categories.' ), "'and'" ) );
  53.   $excluded_categories = explode( ' and ', $excluded_categories );
  54.   } else {
  55.   $excluded_categories = explode( ',', $excluded_categories );
  56.   }
  57.   }
  58.  
  59.   $excluded_categories = array_map( 'intval', $excluded_categories );
  60.  
  61.   if ( ! empty( $cat_array ) ) {
  62.   $excluded_categories = array_diff($excluded_categories, $cat_array);
  63.   $posts_in_ex_cats_sql = '';
  64.   }
  65.  
  66.   if ( !empty($excluded_categories) ) {
  67.   $posts_in_ex_cats_sql = " AND tt.taxonomy = 'category' AND tt.term_id NOT IN (" . implode($excluded_categories, ',') . ')';
  68.   }
  69.   }
  70.   }
  71.  
  72.   $adjacent = $previous ? 'previous' : 'next';
  73.   $op = $previous ? '<' : '>';
  74.   $order = $previous ? 'DESC' : 'ASC';
  75.  
  76.   $join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories );
  77.   $where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories );
  78.   $sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
  79.  
  80.   $query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort";
  81.   $query_key = 'adjacent_post_' . md5($query);
  82.   $result = wp_cache_get($query_key, 'counts');
  83.   if ( false !== $result )
  84.   return $result;
  85.  
  86.   $result = $wpdb->get_row("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");
  87.   if ( null === $result )
  88.   $result = '';
  89.  
  90.   wp_cache_set($query_key, $result, 'counts');
  91.   return $result;
  92.   }
  93.  ?>

これでループ作らなくても利用できる。

functions.php
  1.  <?php
  2.  $next = my_get_adjacent_post(5, false, false, false);
  3.  $prev = my_get_adjacent_post(5);
  4.  
  5.  echo $next->title;
  6.  echo $prev->title;
  7.  ?>

それにしてもループ内でしか使えないとかおかしいので、実はちゃんととれる関数があるかもしれない。

トラックバック(2)

2012年1月14日 05:55

[WordPress] テンプレートのごちゃごちゃが限界にきたのでラッパー書いてみた。WEBプログラム覚書

テンプレートのごちゃごちゃが限界にきたのでラッパー書いてみた。でも僕なんかではなくもっとデキる人が書いたものを使いたいw続きを読む

2012年2月 1日 03:57

[WordPress]管理画面のフッタのフィルタとアクション。WEBプログラム覚書

会員制サイトなどで不特定多数の人にログインさせる場合、フッタのバージョン情報は隠しておきたかったり、 こじゃれたメッセージを表示したいときとか使うアクショ...続きを読む

コメント

コメントする
Name
Email Address
URL
TIME LINE
2012
02.23

[Ubuntu]Gimp gimp-painterとショートカットの設定

デフォルトで入ってるGimpにG-PenMixBrushというのを追加すると お絵描きツールとして利用できるみたいなので入れてみた。OSはUbuntu11.10。

2012
02.22

[Ubuntu]動画ダウンロードと検索が簡単にできるGMediaFinder

Youtubeなどから動画を検索、ダウンロードが出来るソフトウェアGMediaFinder。 登録とか広告とか一切ありませんUbuntu版は。Windows版もありますよ。

2012
02.21
2012
02.20

[イラスト]きれいな線のイラストを簡単に描くには?

噂のGumroadを使いたくてTwitterのアカウント作った。タマゴだと友達が出来ないみたいなのでアイコン描こうと思った。 絵を描かなくなって軽く8年は経っていて、トレス台も行方不明だったので初めて下書きから全部デジタルでやってみたんだけど、やばい。

デジタルやばい。

2012
02.15

[WordPress] get_header()とwp_head()を捨てる。

捨てることで何かメリットがあるかと言うと残念ながら特にありませんので、この内容をオススメしてるわけではありません。

2012
02.14

[Eclipse]PDTのデバック構成でURLの自動生成が表示されない。

Linux 版のPDT3.0.2でデバック構成ウィンドウから新規作成するとURLの自動生成が表示されない。

2012
02.13

[PHP]Xdebugでvar_dump()の出力が省略されて困る場合の対応

Xdebugを利用している場合、var_dump()の出力が省略されて困る場合、 xdebug.iniかini_set()で設定する。

2012
02.10

[雑記]縦横がランダムな要素を隙間なく並べるのは無理なのか。

サイトマップ作ったんだけど、やりたかったことが出来なかった。

2012
02.08

[Ubuntu11.10]Winows XPユーザーがUbuntuを使ってみて

Windows XPとUbuntuのデュアルブート環境にしてみておもったこと。