0

Getting "There has been a critical error on this website." when testing the route https://www.my-site.com/wp/wp-json/project/v3/post/my-wp-post-slug with Postman.

In error_log I see: "PHP Fatal error: Uncaught Exception: NoSuchPostBySpecifiedID in /home/.../functions.php:139".

Considering my code below, what am I doing wrong?

function get_post_by_slug($slug){
  $posts = get_posts(array(
    'name' => $slug,
    'posts_per_page' => 1,
    'post_type' => 'product',
    'post_status' => 'publish'
  ));
  
  if(!$posts) {
    throw new Exception("NoSuchPostBySpecifiedID");
  }
  return $post[0];
}

function single_project($data) {
  $post_slug = $data['slug'];
  $post = get_post_by_slug($post_slug);
  $post->acf = get_fields($post_ID);
  return $post;
}
    
add_action('rest_api_init', function () {
  register_rest_route( 'project/v3', 'post/(?P<slug>[a-zA-Z0-9-]+)', array(
    'methods' => 'GET',
    'callback' => 'single_project',
    'args' => [
      'slug'
    ]
  ));
});
8
  • What exactly is the critical error?
    – shanebp
    Commented Dec 16, 2023 at 21:29
  • I just saw it in error_log, it says: "PHP Fatal error: Uncaught Exception: NoSuchPostBySpecifiedID in /home/.../functions.php:139"
    – drake035
    Commented Dec 16, 2023 at 21:54
  • Does this answer your question? WP REST API -- How to change HTTP Response status code?
    – birgire
    Commented Dec 16, 2023 at 22:38
  • @birgire uh, not at all lol.
    – drake035
    Commented Dec 16, 2023 at 23:46
  • you are throwing an exception when slug not found, return a WP_Error instead like explained there
    – birgire
    Commented Dec 17, 2023 at 0:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.