-
-
Save dexit/6d394fcfe270e2dd6f5133c3e9285437 to your computer and use it in GitHub Desktop.
Creating custom REST endpoints in #WordPress (Custom API)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('rest_api_init', 'register_rest_routes' ); | |
function register_rest_routes(){ | |
// URL will be /wp-json/custom-route/v1/add-list | |
register_rest_route( 'custom-route/v1', 'add-list',array( | |
'methods' => 'POST', | |
'callback' => array('Custom_InfusionWP', 'add_list'), | |
'permission_callback' => function() { | |
return current_user_can('edit_posts'); // Can just return true if it's a public endpoint | |
} | |
)); | |
} | |
function add_to_list($response){ | |
write_log('From our API call'); | |
//write_log($_POST); | |
write_log( $response->get_json_params() ); // If payload is sent as a JSON body, this is how you access | |
wp_send_json_success( $_POST ); | |
} | |
// Alt method | |
add_action( 'wp_ajax_add_to_list', array( $this, 'add_to_list' ) ); | |
add_action( 'wp_ajax_nopriv_add_to_list', array( $this, 'add_to_list' ) ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to pass user nonce through PHP | |
async search( searchTerm ) { | |
let data = { | |
"searchTerm": "foo", | |
}; | |
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch | |
// Ref 2: https://stackoverflow.com/a/43263012 | |
let results = await fetch(this.apiUrl + 'search-orgs', { | |
method: "POST", // *GET, POST, PUT, DELETE, etc. | |
mode: "cors", // no-cors, *cors, same-origin | |
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached | |
credentials: "same-origin", // include, *same-origin, omit | |
headers: { | |
"Content-Type": "application/json", | |
// 'Content-Type': 'application/x-www-form-urlencoded', | |
"X-WP-Nonce": "<?php echo wp_create_nonce('wp_rest'); ?>", | |
}, | |
redirect: "follow", // manual, *follow, error | |
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url | |
body: JSON.stringify(data), // body data type must match "Content-Type" header | |
}); | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment