特定のカスタムフィールドを持つ投稿の除外 (空の記事を表示させる)
特定のカスタムフィールドを持つ投稿を除外する方法(力技)
解決したので、書いておく。
いろいろ調べた結果、meta_queryやmeta_key、meta_value、meta_compareを設定し、「!=」や「NOT IN」や「NOT LIKE」を試したが、カスタムフィールドが空なのではなくの”そのkeyを持っているわけではない”ので検索にヒットしないのでは、という結論に。
調べていた中で、使えそうだった以下のフォーラムを参考に力技で除外してみた。
流れ
- あるカスタムフィールドを持つ記事の記事IDを取得
- excludeで除外
ソース
single.phpの中で、関連するアイテムを表示させる様な場所を想定
下の例ではカスタムフィールド「check」にチェックが入っている記事を除外する
<?php //投稿のカテゴリー情報を取得 $cat = get_the_category(); $catparent = $cat[0]->category_parent; $catcurrent = $cat[0]->cat_ID; //そのカテゴリーの記事数を取得 $cat_count = get_category($catcurrent)->category_count; //1.カスタムフィールドcheckを持つ記事を取得。 //numberpostsは大元の設定に依存するのでここで指定する $exclude_post = array( 'category' => $catcurrent , 'numberposts' => $cat_count, 'meta_query' => array( array( 'key' => 'check', 'value' => 'check', ) ) ); //foreachでcheckをもつ記事のIDを取得 $postslist = get_posts( $exclude_post ); foreach($postslist as $postval){ $result[] = $postval->ID; }; //配列をカンマ区切りに $result_e = implode(",", $result); //2.excludeで除外し、それ以外の記事を5件表示 $args = array( 'numberposts' => 5, 'orderby' => 'rand' , 'category' => $catcurrent , 'exclude' => $result_e, ); $posts = get_posts($args); global $post; ?> <?phpif($posts): foreach($posts as $post): setup_postdata($post); ?> // //記事投稿部分 //
2015/5/7追記
- excludeしたい記事の件数が1000件以上になると読み込みがタイムアウトするので、注意
参考
- 配列をカンマ区切りで出力させる
- カテゴリーの記事数