使用Meta Field创建帖子 - WP REST API

时间:2017-04-04 09:46:15

标签: wordpress wordpress-rest-api

我刚开始使用REST API并使用它来创建来自前端的帖子。我设法用Title,Excerpt,Content发布帖子。 我想添加自定义元字段值,任何示例或帮助都非常感谢。

这是我的Ajax代码,所有其他字段都正常工作,但未在帖子中添加元值

jQuery( document ).ready( function ( $ ) {
$( '#post-submission-form' ).on( 'submit', function(e) {
    e.preventDefault();
    var title = $( '#post-submission-title' ).val();
    var excerpt = $( '#post-submission-excerpt' ).val();
    var content = $( '#post-submission-content' ).val();
    var status = 'draft';

    var data = {
        title: title,
        excerpt: excerpt,
        content: content,
        status: status,
        meta: {
            'video_url_url' : 'abc',
        }

    };

    $.ajax({
        method: "POST",
        url: POST_SUBMITTER.root + 'wp/v2/posts',
        data: data,
        beforeSend: function ( xhr ) {
            xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
        },
        success : function( response ) {
            console.log( response );
            alert( POST_SUBMITTER.success );
        },
        fail : function( response ) {
            console.log( response );
            alert( POST_SUBMITTER.failure );
        }

    });

});

});

3 个答案:

答案 0 :(得分:1)

将此添加到你的functions.php:

/**
 * Add the meta fields to REST API responses for posts read and write
 * Read and write a post meta fields in post responses
 */
function mg_register_meta_api() {
    //Meta Fields that should be added to the API 
    $meta_fields = array(
        'video_url_url',
        'another_meta_key'
    );
    //Iterate through all fields and add register each of them to the API
    foreach ($meta_fields as $field) {
        register_rest_field( 'ring',
            $field,
            array(
                'get_callback'    => array( $this, 'mg_fw_get_meta'),
                'update_callback' => array( $this, 'mg_fw_update_meta'),
                'schema'          => null,
            )
        );
    }
}
add_action( 'rest_api_init', 'mg_register_meta_api' );

/**
 * Handler for getting custom field data.
 *
 * @since 0.1.0
 * 
 * @param array $object The object from the response
 * @param string $field_name Name of field
 *
 * @return mixed
 */
function mg_get_meta( $object, $field_name ) {
    return get_post_meta( $object[ 'id' ], $field_name );
}

/**
 * Handler for updating custom field data.
 *
 * @since 0.1.0
 * @link  http://manual.unyson.io/en/latest/helpers/php.html#database
 * @param mixed $value The value of the field
 * @param object $object The object from the response
 * @param string $field_name Name of field
 *
 * @return bool|int
 */
function mg_update_meta( $value, $object, $field_name ) {
    if ( ! $value || ! is_string( $value ) ) {
        return;
    }

    return update_post_meta( $object->ID, $field_name, maybe_serialize( strip_tags( $value ) ) );
}

现在,您应该能够使用api读取和写入元素'video_url_url'。

答案 1 :(得分:0)

我今天正在研究这个问题,并提出了以下解决方案,该解决方案效果很好,并添加了多个字段。

希望这对可能会卡在其中的人有所帮助。

    add_action( 'rest_api_init', 'foo_register_meta_api' );

    function foo_register_meta_api() {
        // Meta Fields to add to the API
        $meta_fields = array(
            'field_1',
            'foo_bar',
            'foobar',
            'another_field'
        );
        // Loop all fields and register each of them to the API
        foreach ($meta_fields as $field) {
            register_rest_field( 'my-post-type',
                $field,
                array(
                    'get_callback'    => function ($params) use ($field) {
                        return \get_post_meta($params['id'], $field);
                    },
                    'update_callback' => function ($value, $object, $fieldName){
                        return \update_post_meta($object->ID, $fieldName, $value);
                    },
                    'schema' => null
                )
            );
        }
    }

答案 2 :(得分:0)

我正在尝试将phy_marks保存为帖子类型candidates。我所能做的就是创建帖子,但没有保存phy_marks

我的JSON数据:

{ "title": "Why not working finally","content": "Test", "status": "publish" ,"post_type": "candidates", "meta": {
  "phy_marks": 66 } }

我的代码:

add_action( 'rest_api_init', 'foo_register_meta_api' );

function foo_register_meta_api() {
    // Meta Fields to add to the API
    $meta_fields = array(
        'phy_marks'
    );
    // Loop all fields and register each of them to the API
    foreach ($meta_fields as $field) {
        register_rest_field( 'candidates',
            $field,
            array(
                'get_callback'    => function ($params) use ($field) {
                    return \get_post_meta($params['id'], $field);
                },
                'update_callback' => function ($value, $object, $fieldName){
                    return \update_post_meta($object->ID, $fieldName, $value);
                },
                'schema' => null
            )
        );
    }
}