在 REST API 中获取自定义字段(meta_key)

问题描述 投票:0回答:1

我有这个功能可以将我的自定义字段保存在 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":"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 中创建的自定义字段吗?

php wordpress wordpress-rest-api
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.