10
12

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.

WP REST API v2でカスタムフィールドを検索する

Last updated at Posted at 2018-02-18

なにこれ

WP REST API v2においてカスタムフィールドを検索する方法

結論


/**
 * 検索クエリをカスタム
 */
add_filter( 'rest_foobar_query', 'my_rest_foobar_query', 10, 2 ); // rest_{post_type}_query

function my_rest_foobar_query( $args, $request ) {
    // ここにでargsをゴニョゴニョする
    return $args;
}

rest_{post_type}_queryのフィルタに追加してやるだけでなんとかなる。$requestはクライアントから送られてきたパラメータ一式が入ってる。

$argshttps://developer.wordpress.org/reference/classes/wp_rest_posts_controller/get_items/ を見てみるとWP_Queryに渡す検索条件

つまりどういうことだってばよ

例えばよくある都道府県で検索したい場合の例
通常の投稿に都道府県をカスタムフィールドとして登録している前提

add_filter( 'rest_post_query', 'my_rest_post_query', 10, 2 ); // rest_{post_type}_query

function my_rest_post_query( $args, $request ) {
  if ( isset( $request['prefecture'] ) ) {
      $args['meta_query'] = array(
        array(
        "key" => "prefecture",
        "value" => $request['prefecture'],
        "compare" => "="
        )
      );
  }
}

以上

10
12
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
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?