Skip to content

Instantly share code, notes, and snippets.

@vanaf1979
Last active April 15, 2024 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vanaf1979/d8561a6e16b2fa992de363f71863434f to your computer and use it in GitHub Desktop.
Save vanaf1979/d8561a6e16b2fa992de363f71863434f to your computer and use it in GitHub Desktop.
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