Search code examples
jsonwordpressionic-frameworkwp-apiwordpress-rest-api

Wordpress REST API 404 error when requesting Custom Post Type with Mobile Browser


I am confused. I am using Wordpress REST Api to build a mobile app with Ionic. I am trying to implement regular post type and one of my custom post type.

I can make a get request for the standard post type "http://www.example.org/wp-json/wp/v2/posts" and it works.

I did the same with my custom post type "http://www.example.org/wp-json/wp/v2/shows" and when I test it in my browser it works BUT when I use chrome and the mobile simulator it gives me an 404 error : rest_no_route

Any ideas why this error occurs, especially only for custom post types?


Solution

  • By default custom post type won't be available. You need to add the below snippets to functions.php of your theme file:

    add_action( 'init', 'custom_post_type_rest_support', 25 );
    function custom_post_type_rest_support() {
      global $wp_post_types;
    
      $post_type_name = 'show';
      if( isset( $wp_post_types[ $post_type_name ] ) ) {
        $wp_post_types[$post_type_name]->show_in_rest = true;
        $wp_post_types[$post_type_name]->rest_base =  $post_type_name ;
        $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
      }
    }