0
0

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 1 year has passed since last update.

WordPress REST API、カスタムフィールドの値で絞り込む

Last updated at Posted at 2022-07-04

はじめに

WordPress REST APIでカスタムフィールドの値で検索(絞り込み)することがあったので、そのときのメモです。

こちらの記事も参考にしました。
WordPress REST APIで記事検索に使うオプションを全て調べた

コード

<?php
add_action( 'rest_api_init', 'add_meta_field_at_product' );
function add_meta_field_at_product()
{
    register_rest_field( 'product',
        'meta_data', 
        [
            'get_callback'  => 'get_callback_for_add_meta_field',
            'update_callback' => null,
            'schema'          => null,
        ]
    );
}

function get_callback_for_add_meta_field($object, $field_name, $request)
{
    _log($request);

    $meta = [];
    $title = $object['title']['rendered'];

    $products = get_fields($object['id']);
    foreach($products as $details) {
        foreach($details as $d) {
            $d['title'] = $title;
            $meta[] = $d;
        }
    }

    return $meta;
}

_logの関数については、こちら参照してください。

callback関数の$requestの中身に検索条件が入ってきます。(後日、サンプル出したいと思います)

条件に合うものだけ、returnすると、絞り込んだものだけが取得できます。

そのうち、ちゃんと解説書きたいと思います!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?