Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to create a custom WordPress Rest Api route. https://since1979.dev/snippet-005-simple-custom-rest-api-route/
<?php
/**
* mytheme_handle_get_meta_value.
*
* Handle calls to the Wp Rest Api /meta end-point,
*
* @see https://since1979.dev/snippet-005-simple-custom-rest-api-route/
*
* @uses get_post_meta() https://developer.wordpress.org/reference/functions/get_post_meta/
* @uses WP_Error() https://developer.wordpress.org/reference/classes/wp_error/
* @uses rest_ensure_response() https://developer.wordpress.org/reference/functions/rest_ensure_response/
* @uses array() https://www.php.net/manual/en/function.array.php
*/
function mytheme_handle_get_meta_value($request)
{
$post = $request['post'];
$key = $request['key'];
$value = get_post_meta($post, $key, true);
if (!$value)
return new WP_Error('Meta value not found', 'Invalid meta key', array('status' => 404));
return rest_ensure_response(array('meta' => $value));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.