WP REST API fetch posts from post type WP REST API fetch posts from post type wordpress wordpress

WP REST API fetch posts from post type


There is a really shot and easy way for v.2. All that you have to do is to include to your args array the following property: 'show_in_rest' => true

Example:

register_post_type( 'recipe',     array(          'labels' => $labels,          'public' => true,          'menu_position' => 5,          'hierarchical' => false,          'supports' => $supports,          'show_in_rest' => true,          'taxonomies' => array('recipe-type', 'post_tag'),          'rewrite' => array( 'slug' => __('recipe', 'recipe') )     ));


To use v2 of the REST API plugin:

In the functions.php file of your theme, add the following to create a rest endpoint:

add_action( 'init', 'add_myCustomPostType_endpoint');function add_myCustomPostType_endpoint(){    global $wp_post_types;    $wp_post_types['myCustomPostType']->show_in_rest = true;    $wp_post_types['myCustomPostType']->rest_base = 'myCustomPostType';    $wp_post_types['myCustomPostType']->rest_controller_class = 'WP_REST_Posts_Controller';}

Now you should have the following endpoint to query from:

/wp-json/wp/v2/myCustomPostType

myCustomPostType being the custom post type that you registered. The "rest_base" does not have to match the name of your custom post type.

You will most likely want to add additional fields that are specific to your custom post type, such as post metadata or perhaps from the Advanced Custom Fields plugin. For those scenarios, you can include those properties by adding a snippet like this to your functions.php file:

function add_myCustomPostType_fields_url_to_myCustomPostType_request( $data, $post, $request ) {    $_data = $data->data;    $customImageProperty = get_field('customImageProperty');     $_data['customImageProperty'] = $customImageProperty['url'];    $data->data = $_data;    return $data;}add_filter( 'rest_prepare_myCustomPostType', 'add_myCustomPostType_fields_url_to_myCustomPostType_request', 10, 3 );


register_post_type('name of post type'...) not the 'add_new' name.Change the name of your post type to Magazine and checkout the result. Hope it helps.