Insert custom post meta value using WP-REST API

I’m using this tutorial to insert a post via front-end using WP-REST API.

I have added more fields to add custom post meta data to the post but while the post is being submitted via the front-end, the custom post meta are not being inserted. I’m not sure where I am going wrong.

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

        });

    });

} );

This is the JSON response I get when I submit. The custom post meta fields are blank:

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

I have added this code in functions.php to expose the meta data in the 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()
        )
    );

});

Read more here: Insert custom post meta value using WP-REST API

Leave a Reply

Your email address will not be published. Required fields are marked *