web-dev-qa-db-ja.com

WP-REST APIを使用してカスタム投稿メタ値を挿入する

私は このチュートリアル を使って、WP-REST APIを使ってフロントエンドで投稿を挿入します。

カスタム投稿メタデータを投稿に追加するためのフィールドを追加しましたが、投稿がフロントエンドを介して送信されている間は、カスタム投稿メタは挿入されません。どこに問題があるのか​​よくわかりません。

Form.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レスポンスです。カスタム投稿メタフィールドは空白です。

{
  "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
      }
    ]
  }
}

REST AP​​Iのメタデータを公開するために、このコードをfunctions.phpに追加しました。

//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
input

まあ、投稿メタを更新する方法があります。 restフィールドを登録するときにupdate_callbackを追加する必要があります。以下の例を見てください。

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');

メタは、新しい投稿を作成するときに送信したJSONオブジェクトのplayer_metaプロパティの下に格納されています。

4
sunpietro