admin管理员组

文章数量:1128305

Getting "There has been a critical error on this website." when testing the route 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'
    ]
  ));
});

本文标签: Custom REST route fetching posts by slug isn39t working