如何使用WordPress rest API更新/插入自定义域(元数据)数据?

时间:2018-01-11 作者:Varun Naharia

我试图通过wordpress API添加自定义帖子数据(帖子元数据),但在更新/添加自定义帖子数据时遇到了困难。下面是我使用的代码。

Code written in function.php

    add_action( \'rest_api_init\', \'create_api_posts_meta_field\' );

function create_api_posts_meta_field() {

 // register_rest_field ( \'name-of-post-type\', \'name-of-field-to-return\', array-of-callbacks-and-schema() )
 register_rest_field( \'experience\', \'subtitle\', array(
 \'get_callback\' => \'get_post_meta_for_api\',
 \'update_callback\'   => \'update_post_meta_for_exp\',
 \'schema\' => null,
 )
 );
}


function update_post_meta_for_exp($object, $meta_value ) {
                $havemetafield  = get_post_meta($object[\'id\'], \'experience\', false);
                if ($havemetafield) {
                    $ret = update_post_meta($object[\'id\'], \'subtitle\', $meta_value );
                    return true;
                } else {
                    $ret = add_post_meta( $object[\'id\'], \'subtitle\', $meta_value ,true );
                    return true;
                }
            }

function get_post_meta_for_api( $object ) {
 //get the id of the post object array
 $post_id = $object[\'id\'];

 //return the post meta
 return get_post_meta( $post_id )["Subtitle"][0];
}

 function create_api_posts_meta_field_time() {



// register_rest_field ( \'name-of-post-type\', \'name-of-field-to-return\', array-of-callbacks-and-schema() )
 register_rest_field( \'experience\', \'timing_of_experience\', array(
 \'get_callback\' => \'get_post_meta_for_api_time\',
 \'update_callback\'   => function($meta_value ) {
                $havemetafield  = get_post_meta(1, \'experience\', false);
                if ($havemetafield) {
                    $ret = update_post_meta(1, \'timing_of_experience\', $meta_value );
                    return true;
                } else {
                    $ret = add_post_meta( 1, \'timing_of_experience\', $meta_value ,true );
                    return true;
                }
            },
 \'schema\' => null,
 )
 );
}

function get_post_meta_for_api_time( $object ) {
 //get the id of the post object array
 $post_id = $object[\'id\'];

 //return the post meta
 return get_post_meta( $post_id )["timing_of_experience"][0];
}
我正在处理的页面中包含的JS文件

var quickAddExperience = document.querySelector("#quick-add-experience");

  if (quickAddExperience) {

        quickAddExperience.addEventListener("click",function() {

                var ourPostData = {
                    \'title\'                  : document.getElementById(\'title\').value,
                    \'content\'                : document.getElementById(\'content\').value,
                    \'subtitle\'               : document.getElementById(\'company_name\').value,
                    \'timing_of_experience\'   : document.getElementById(\'time_period\').value,
                    \'status\'                 : \'publish\'
                }

                console.log(ourPostData);
                var createPost = new XMLHttpRequest();
                createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/experience-api");
                createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
                createPost.setRequestHeader("Content-Type","application/json;charset=UTF-8");
                createPost.send(JSON.stringify(ourPostData));
                createPost.onreadystatechange = function(){
                    if (createPost.readystate == 4) {
                        if (createPost.status == 201) {
                                document.querySelector(\'.data-api-post-1 [name="title"]\').value =\'\';
                                document.querySelector(\'.data-api-post-1 [name="content"]\').value =\'\';
                                document.querySelector(\'.data-api-post-1 [name="company_name"]\').value =\'\';
                                document.querySelector(\'.data-api-post-1 [name="time_period"]\').value =\'\';
                        }else{
                            alert("Error - try again");
                        }
                    }
                }


        });
    }
此代码适用于默认字段,意味着创建了新帖子,但只有标题和内容。

Edit:当我尝试调试时,才知道update\\u回调代码没有执行,但get\\u回调正在执行。

2 个回复
最合适的回答,由SO网友:Andrei 整理而成

我刚刚用您的代码运行了一个测试,在我看来,这不起作用,因为您在get_callback 作用

第一次尝试subtitle(或timing_of_experience) 但它将触发一个错误,因为它首先不存在,并且此错误将阻止update_callback.

所以,问题是get_callback 这个Subtitle 钥匙有一个大写字母S 这不是拯救它的方式。

其次,您应该遵守验证数据的一般规则,并在尝试访问数据之前检查该值是否存在。像这样:

function get_post_meta_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object[\'id\'];

    $meta = get_post_meta( $post_id );

    if ( isset( $meta[\'subtitle\' ] ) && isset( $meta[\'subtitle\' ][0] ) ) {
        //return the post meta
        return $meta[\'subtitle\' ][0];
    }

    // meta not found
    return false;
}
就像我说的,我做了一个测试experience 具有的帖子类型post 它正在发挥作用。

额外提示,您应该尝试更好地组织代码,因为这种缩进和函数顺序很难阅读。此外,对于update_callback 一个简单的return true 足够了。

function update_post_meta_for_exp($object, $meta_value ) {
    $havemetafield  = get_post_meta($object[\'id\'], \'experience\', false);
    if ($havemetafield) {
        $ret = update_post_meta($object[\'id\'], \'subtitle\', $meta_value );
    } else {
        $ret = add_post_meta( $object[\'id\'], \'subtitle\', $meta_value ,true );
    }
    return true;
}

SO网友:Muddasir

您可以使用以下代码编写自定义post数据。我使用下面的代码在WordPress API中编写自定义帖子类型“ad\\U portfolio”类别和特色图片。希望有帮助。谢谢你

    function prepare_rest($data, $post, $request){
    $_data = $data->data;

    $thumbnail_id = get_post_thumbnail_id( $post->ID );
    $featured_media_url = wp_get_attachment_image_src( $thumbnail_id, \'large\' );

    $post_categories = wp_get_post_terms( $post->ID, \'ad_portfolios\' , array("fields" => "all") );
    $cats = array();

    foreach($post_categories as $cat){
        $cats[] = [\'slug\' => $cat->slug, \'name\' => $cat->name ];
    }

    $_data[\'featured_media_url\'] = $featured_media_url[0];
    $_data[\'portfolio_cats\'] = $cats;
    $data->data = $_data;

    return $data;
}
add_filter(\'rest_prepare_ad_portfolio\', \'prepare_rest\', 10, 3);
//post type is "ad_portfolio"

结束

相关推荐

通过WP-API提供的类别上的额外字段?

我希望我的帖子属于一个分类法,并带有几个额外的字段,例如category_icon, category_quick_facts 我希望这个分类法(及其所有字段)可以通过WP-API获得。如何设置?(我更喜欢没有插件的解决方案,但只要该解决方案能与WP-API配合使用,我将不胜感激。)