3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPressでカスタムフィールドの条件を指定してカスタム投稿タイプの投稿を取得してみる

Last updated at Posted at 2018-07-10

どうも、はぐっです・ω・♪

WorePressでカスタム投稿タイプを扱う

「WordPressでカスタムフィールドの条件を指定してカスタム投稿タイプの投稿を取得するにはどうしたらええんや」
っていう壁にぶち当たった話をします。

さぁ。

どうやって取んねん。

魔法の言葉、get_posts

get_posts、なんてわかりやすい響き。そのまんま、投稿をげっとー。

今回の登場人物

$args      : 取得条件
$post_type : 取得したいカスタム投稿タイプ
$key       : 条件として指定するカスタムフィールドのフィールド名(キー)
$value     : 条件として指定するカスタムフィールドの値
$posts     : 取得した投稿

条件として指定するカスタムフィールドが一つの場合

$args = array(
  'numberposts' => 5, // 取得数
  'post_type'   => $post_type,
  'meta_key'    => $key,
  'meta_value'  => $value
);

$posts = get_posts($args);

はいげっとー。

条件として指定するカスタムフィールドが複数の場合

$key1   : 条件として指定するカスタムフィールドのフィールド名1(キー)
$key2   : 条件として指定するカスタムフィールドのフィールド名2(キー)
$value1 : 条件として指定するカスタムフィールドの値1
$value2 : 条件として指定するカスタムフィールドの値2
$args = array(
  'numberposts' => 5, // 取得数
  'post_type'   => $post_type,
  'meta_query'  => array(
    array(
      'key'   => $key1,
      'value' => $value1
    ),
    array(
      'key'   => $key2,
      'value' => $value2
    )
  )
);

$posts = get_posts($args);

はいげっとー。

ってな感じで、カスタムフィールドの条件を指定してカスタム投稿タイプの投稿を取得できました。

カスタム投稿タイプは、WordPressでなにかしらを作ろうとした時、かなりよく使う機能なので、今回取り上げたget_postsを使うときはかなり訪れるかと思います。

ちなみに、

$args = array(
  'order' => 'DESC'
);

で、降順に取得したりと、get_postsには様々な装備(オプション)をつけることができます。
詳細はWE…公式サイトで。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?