LoginSignup
1
1

More than 5 years have passed since last update.

get_postsを用いてカテゴリーとカスタムフィールドの複合条件で投稿を取得する

Last updated at Posted at 2018-07-06

WordPressで作ったサイトの変更案件で下記の条件に該当する投稿一覧を取得するコトになった。

  • 複数のカテゴリーに該当しない
  • 特定のカスタムフィールドに値が設定されたコトがない または 特定のカスタムフィールドの値が1ではない

ということで、get_postsの検索条件をゴニョゴニョと変更

$args = array(
    'post_type' => 'post',     // 投稿タイプ
    'posts_per_page' => 3,     // 取得件数
    'cat' => array(-1, -2,),   //除外するカテゴリーID。categoryではなくcat。AND条件。
    'meta_query' => array(
        // hogehogeという特定のカスタムフィールドの値が1ではない
        array(
            'key' => 'hogehoge',
            'value' => 1,
            'compare' => '!=',
        ),
        // hogehogeという特定のカスタムフィールドの値が一度も設定されたコトが無い
        array(
            'key' => 'hogehoge',
            'compare' => 'NOT EXISTS',
        ),
        // OR条件で検索する
        'relation' => 'OR',
    ),
    'order' => 'DESC',         // 並び順
    'orderby' => 'date',       // 並び順のキー
);
$posts = get_posts($args);

カテゴリーIDは管理画面のクエリ文字列(tag_id)で確認できます。

参考にさせてもらいました

1
1
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
1
1