web-dev-qa-db-fra.com

Insertion d'une post valeur méta personnalisée à l'aide de l'API WP-REST

J'utilise ce tutoriel pour insérer un message via front-end à l'aide de l'API WP-REST.

J'ai ajouté plus de champs pour ajouter des métadonnées de publication personnalisées à la publication mais, alors que la publication est soumise via le serveur frontal, les méta de publication personnalisées ne sont pas insérées. Je ne sais pas trop où je vais mal.

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

        });

    });

} );

C'est la réponse JSON que je reçois lorsque je soumets. Les champs de méta post personnalisés sont vides:

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

J'ai ajouté ce code dans functions.php pour exposer les métadonnées de l'API REST:

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

Eh bien, il existe un moyen de mettre à jour la méta post. Vous devez ajouter le update_callback lors de l'enregistrement du champ de repos. Voir l'exemple ci-dessous:

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

La méta est stockée sous la propriété player_meta dans votre objet JSON que vous envoyez lors de la création d'une nouvelle publication.

4
sunpietro