WP REST API fetch posts from post type

Just add the next parmater into the function register_post_type, it can be before ‘menu_position’parameter. ‘show_in_rest’ => true

enter image description here

if you’re using a plugin to register your posttype you can use the next code:

add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
    global $wp_post_types;
    $wp_post_types['anuncio']->show_in_rest = true;
}

after that, you’ll be able to list your posts from mydomain.com/wp-json/wp/v2/posttype_slug

in my case: mydomain.com/wp-json/wp/v2/anuncio

you can also register a new base using the next code:

add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
    global $wp_post_types;
    $wp_post_types['anuncio']->show_in_rest = true;
    $wp_post_types['anuncio']->rest_base="clasi";
    $wp_post_types['anuncio']->rest_controller_class="WP_REST_Posts_Controller";
}

just replace anuncio for your post type slug and ‘clasi’ will be your route. mydomain.com/wp-json/wp/v2/clasi

Leave a Comment