在rest API中获取自定义fieds(meta_key)

时间:2018-02-10 01:20:13

标签: wordpress wordpress-rest-api

我有这个功能,我的自定义字段保存在WP数据库中(这是工作和保存):

function notifyem_save_post() {
    if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new? 
    global $post;
    update_post_meta($post->ID, "country", $_POST["country"]);
    update_post_meta($post->ID, "region", $_POST["region"]);
    update_post_meta($post->ID, "time", $_POST["time"]);
    update_post_meta($post->ID, "activity", $_POST["activity"]);
}     

我想从REST API中显示它们,但只显示TITLE:

[{"title":"john"},{"title":"xxx"},{"title":"11"}]

这是我的REST API GET的代码

function notifyem_rest_get() {
    $subscriptions = new WP_Query(array(
        'post_type' => 'notifyem'
    ));
    $subscriptionResults = array();
    register_rest_route('notifyemAPI/v1', '/subscription', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => array($this, 'getSubscription')
    ));
}

function getSubscription() {
    $subscriptions = new WP_Query(array(
        'post_type' => 'notifyem',
        'meta_key' => 'country'
    ));

    $subscriptionResults = array();

    while($subscriptions->have_posts()) {
        $subscriptions->the_post();
        array_push($subscriptionResults, array(
            'region' => get_field('regi'),
            'country' => get_field('country'),
            'activity' => get_field('activity'),
            'time' => get_field('time')
        ));
    }
    return $subscriptionResults;
}

下面的屏幕显示是插入我的自定义帖子类型的字段。

enter image description here

如何获取我在REST API中创建的自定义字段的任何想法?

1 个答案:

答案 0 :(得分:0)

试试此代码

 function getSubscription() {
    $subscriptions = new WP_Query(array(
        'post_type' => 'notifyem',
        'meta_key' => 'country'
    ));

    $subscriptionResults = array();

    while($subscriptions->have_posts()) {
        $subscriptions->the_post();
        array_push($subscriptionResults, array(
            'region' =>  get_post_meta(the_ID(), "region", true),
            'country' =>get_post_meta(the_ID(), "country", true),
            'activity' => get_post_meta(the_ID(), "activity", true),
            'time' => get_post_meta(the_ID(), "time", true)
        ));
    }
    return $subscriptionResults;
}