Skip to content

Instantly share code, notes, and snippets.

@xeiter
Created December 14, 2016 04:04
Show Gist options
  • Save xeiter/78d8c3657cd51fc71e6764ea156fb2f6 to your computer and use it in GitHub Desktop.
Save xeiter/78d8c3657cd51fc71e6764ea156fb2f6 to your computer and use it in GitHub Desktop.
WP Rest API example
<?php
// Register a new route
add_action( 'rest_api_init', function () {
register_rest_route( 'portal/v1', '/messages/favourite/toggle', array(
'methods' => 'POST',
'callback' => 'change_favorite_status_of_a_message',
) );
} );
function change_favorite_status_of_a_message( $data ) {
$message_id = $data->get_param('id');
$state = $data->get_param('state');
// Get instance of goTandem API
$gt = BbGoTandem::get_instance();
// Update the favorite status of a message
$result = $gt->update_message( $message_id, [ 'favorite' => $state ] );
return $result;
}
(function($) {
$(".favorite-icon").on("click", function() {
$.ajax( {
url: wpApiSettings.root + 'portal/v1/messages/favourite/toggle',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'id': $(this).data("msgid"),
'state': $(this).data("state"),
}
} ).done( function ( response ) {
// console.log( response );
} );
});
})( jQuery );
<?php
wp_enqueue_script( 'wp_rest_js', plugins_url( 'javascript.js', __FILE__ ) , array('jquery'), '1.0.0', true );
<!-- Link that triggers the WP Rest API call -->
<a class="favorite-icon" data-msgid="<?= $message_id ?>" data-state="<?= $favorite_value ?>" href="#">
<i aria-hidden="true" class="fa <?= $star_class; ?>"></i>
</a>
<?php wp_localize_script( 'wp_rest_js', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) ); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment