使用WP-REST API插入自定义发布元值

时间:2017-04-06 作者:input

我正在使用this tutorial 使用WP-REST API通过前端插入post。

我已经添加了更多字段来向帖子中添加自定义帖子元数据,但是当帖子通过前端提交时,自定义帖子元数据没有被插入。我不确定我会错在哪里。

类型php:

<?php
/**
 * Template Name: Form
 */

get_header();

?>

<form id="post-submission-form" name="mysite-add" method="POST">

        <div>
                    <label for="mysite-name">
                        <?php _e( \'Name\', \'mysite\' ); ?>
                    </label>
                    <input type="text" name="mysite-name" id="mysite-name" required aria-required="true">
                </div>

        <div>
                    <label for="mysite-address">
                        <?php _e( \'Address\', \'mysite\' ); ?>
                    </label>
                    <input type="text" name="mysite-address" id="mysite-address" required aria-required="true">
                </div>

        <div>
                    <label for="mysite-contact">
                        <?php _e( \'Contact\', \'mysite\' ); ?>
                    </label>
                    <input type="text" name="mysite-contact" id="mysite-contact" required aria-required="true">
                </div>

        <div>
                    <label for="mysite-sm-fb">
                        <?php _e( \'Facebook\', \'mysite\' ); ?>
                    </label>
                    <input type="text" name="mysite-sm-fb" id="mysite-sm-fb" required aria-required="true">
                </div>

        <div>
                    <label for="mysite-sm-insta">
                        <?php _e( \'Instagram\', \'mysite\' ); ?>
                    </label>
                    <input type="text" name="mysite-sm-insta" id="mysite-sm-insta" required aria-required="true">
                </div>

                <input type="submit" value="<?php esc_attr_e( \'Submit\', \'mysite\'); ?>">
            </form>
jQuery:

jQuery( document ).ready( function ( $ ) {
    $( \'#post-submission-form\' ).on( \'submit\', function(e) {
        e.preventDefault();
        var name = $( \'#mysite-name\' ).val();
        var address = $( \'#mysite-address\' ).val();
        var contact = $( \'#mysite-contact\' ).val();
        var sm_fb = $( \'#mysite-sm-fb\' ).val();
        var sm_insta = $( \'#mysite-sm-insta\' ).val();
        var status = \'draft\';

        var sm = [{ \'social-media\': [sm_fb, sm_insta], \'contact\' : contact, \'address\' : address}];

        console.log(sm);
        var data = {
            title: name,
            groups: category,
            jmeta: sm,
        };

        $.ajax({
            method: "POST",
            url: POST_SUBMITTER.root + \'wp/v2/business\',
            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 );
            }

        });

    });

} );
这是我提交时得到的JSON响应。自定义post meta字段为空:

{
  "id": 78,
  "date": "2017-04-06T19:05:36",
  "date_gmt": "2017-04-06T18:05:36",
  "guid": {
    "rendered": "http://example.com/?post_type=custom-post-type&p=78",
    "raw": "http://example.com/?post_type=custom-post-type&p=78"
  },
  "modified": "2017-04-06T19:05:36",
  "modified_gmt": "2017-04-06T18:05:36",
  "password": "",
  "slug": "",
  "status": "draft",
  "type": "custom-post-type",
  "link": "http://example.com/?post_type=custom-post-type&p=78",
  "title": {
    "raw": "adasd",
    "rendered": "adasd"
  },
  "content": {
    "raw": "adasd",
    "rendered": "<p>adasd</p>\\n",
    "protected": false
  },
  "excerpt": {
    "raw": "",
    "rendered": "<p>adasd</p>\\n",
    "protected": false
  },
  "author": 1,
  "featured_media": 0,
  "menu_order": 0,
  "comment_status": "open",
  "ping_status": "closed",
  "template": "",
  "format": "standard",
  "meta": [],
  "groups": [
    5
  ],
  "address": "",
  "jmeta": [
    {
      "social-media": [],
      "address": "",
      "contact": "",
      "rating": ""
    }
  ],
  "_links": {
    "self": [
      {
        "href": "http://example.com/wp-json/wp/v2/custom-post-type/78"
      }
    ],
    "collection": [
      {
        "href": "http://example.com/wp-json/wp/v2/custom-post-type"
      }
    ],
    "about": [
      {
        "href": "http://example.com/wp-json/wp/v2/types/custom-post-type"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "http://example.com/wp-json/wp/v2/users/1"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "http://example.com/wp-json/wp/v2/comments?post=78"
      }
    ],
    "wp:attachment": [
      {
        "href": "http://example.com/wp-json/wp/v2/media?parent=78"
      }
    ],
    "wp:term": [
      {
        "taxonomy": "groups",
        "embeddable": true,
        "href": "http://example.com/wp-json/wp/v2/groups?post=78"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}
我已将此代码添加到functions.php 要在REST API中公开元数据,请执行以下操作:

//Add custom field to REST API
function filter_post_json( $data, $post, $context ) {
  $address = get_post_meta( $post->ID, \'address\', true );
  $contact = get_post_meta( $post->ID, \'contact\', true );
  $rating = get_post_meta( $post->ID, \'rating\', true );
  $social_media = get_post_custom_values( \'social-media\' );

  $sm = [];
  if($social_media):
    foreach ( $social_media as $key => $value ) {
      $sm[]  = $value;

    }
  endif;
  $data->data[\'jmeta\'][] = array( \'social-media\' => $sm, \'address\' => $address, \'contact\' => $contact, \'rating\' => $rating );
  $data->data[\'address\'] = $address;
    return $data;
}
add_filter( \'rest_prepare_custom-post-type\', \'filter_post_json\', 10, 3 );

add_action( \'wp_enqueue_scripts\', function() {

    //load script
    wp_enqueue_script( \'my-post-submitter\', plugin_dir_url( __FILE__ ) . \'post-submitter.js\', array( \'jquery\' ) );

    //localize data for script
    wp_localize_script( \'my-post-submitter\', \'POST_SUBMITTER\', array(
            \'root\' => esc_url_raw( rest_url() ),
            \'nonce\' => wp_create_nonce( \'wp_rest\' ),
            \'success\' => __( \'Thanks for your submission!\', \'mysite\' ),
            \'failure\' => __( \'Your submission could not be processed.\', \'mysite\' ),
            \'current_user_id\' => get_current_user_id()
        )
    );

});

1 个回复
SO网友:sunpietro

嗯,有一种方法可以更新post meta。您必须添加update_callback 注册rest字段时。请参见以下示例:

function rest_api_player_meta() {
    register_rest_field(\'sp_player\', \'player_meta\', array(
            \'get_callback\' => \'get_player_meta\',
           \'update_callback\' => \'update_player_meta\',
           \'schema\' => null,
        )
    );
}

function get_player_meta($object) {
    $postId = $object[\'id\'];

    return get_post_meta($postId);
}

function update_player_meta($meta, $post) {
    $postId = $post->ID;

    foreach ($meta as $data) {
        update_post_meta($postId, $data[\'key\'], $data[\'value\']);
    }
}

add_action(\'rest_api_init\', \'rest_api_player_meta\');
元数据存储在player_meta 创建新帖子时发送的JSON对象中的属性。