最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I add a meta[] to my custom post type and search by term with the Rest API?

programmeradmin1浏览0评论

I just started to use the Rest API and I want to get all posts that belong to a certain taxonomy and term(s) within that taxonomy. That part is working now.

Then I want the those posts to have a meta[] with their fields. I found multiple articles about this but the code did not seem to work. The meta[] is still empty. I want it to add all the fields in there. I'm sure that they have meta because I managed to do it in the old legacy way and that worked.

/

/

I also noticed that the response is an object, shouldn't it be json?

Ajax Request

function do_make_rest_api_call()
{
    return '<script>
        $.ajax({
             url: "/wp-json/wp/v2/verhuur?productcategorie=413&per_page=100",
             type: "GET",
        }).then(response => {
            console.log(typeof response);
            console.log(response);
            var json = JSON.parse(response);
            console.log(json);
        });

    </script>';
}
add_shortcode('first_rest_api_call', 'do_make_rest_api_call');

Field Register(register individual fields, I want all the fields in the meta[])

add_action('rest_api_init', function () {
    register_rest_field('verhuur', 'product', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'product', true);
        },
    ));
    register_rest_field('verhuur', 'voorraad', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'voorraad', true);
        },
    ));
    register_rest_field('verhuur', 'ex_btw', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'ex_btw', true);
        },
    ));
    register_rest_field('verhuur', 'incl_btw', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'incl_btw', true);
        },
    ));
    register_rest_field('verhuur', 'groeps_nmr', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'groeps_nmr', true);
        },
    ));
    register_rest_field('verhuur', 'bestel_code', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'bestel_code', true);
        },
    ));
    register_rest_field('verhuur', 'datum_aangepast', array(
        'get_callback' => function ($post_arr) {
            return get_post_meta($post_arr['id'], 'datum_aangepast', true);
        },
    ));
});
发布评论

评论列表(0)

  1. 暂无评论