So far, I have created a plugin that creates an input form, registers a custom endpoint and enqueues a supporting script:
plugin.php
// Create Input Form
<?php
function mysite_input_form(){
?>
<form id="site-name-form" class="site-name-form">
<div>
<label class="site-name-input-label" for="site-name-input">
<?php _e( 'Site Name', 'mysite' ); ?>
</label>
<input type="text" name="site-name-input" id="site-name-input" class="site-name-input">
</div>
<input type="submit" value="<?php esc_attr_e( 'Submit', 'mysite'); ?>">
</form>
<?php
}
// Register Custom Endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'mysite-info/v1', '/name/', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_item',
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => 'update_item',
),
));
});
//Equeue Script
function plugin_scripts(){
//load script
wp_register_script( 'plugin-script', plugins_url( '/js/plugin-script.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'plugin-script' );
//localize data for script
wp_localize_script( 'plugin-script', 'FORM_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()
)
);
}
add_action( 'admin_enqueue_scripts', 'plugin_scripts' );
plugin-script.js
jQuery( document ).ready( function ( $ ) {
$( '#site-name-form' ).on( 'submit', function(e) {
e.preventDefault();
var name = $('.site-name-input').val();
var data = {
name: name
};
$.ajax({
method: "PUT",
url: FORM_SUBMITTER.root + 'mysite-info/v1/name',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', FORM_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( FORM_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( FORM_SUBMITTER.failure );
}
});
});
});
I am using the “PUT” method because I want to update the value of the blog name in the database.
The main thing I’m struggling with is understanding what else is needed for this to work. The WP API docs show that you need a callback to actually update the value in the database.
I would think this would work:
function update_item( $request ) {
update_option( 'blogname', $request );
}
However when I submit the inputed value, nothing happens. It’s doesn’t even seem to hit the ajax “fail” case.
Please help me figure out what I am missing.