How to get custom post types in the WP-API v2?

Picture of Woocoders
Woocoders
11th July 2021

Method 1:

/**
 * Register a book post type, with REST API support
 *
 * Based on example at: https://codex.wordpress.org/Function_Reference/register_post_type
 */
add_action( 'init', 'my_event_cpt' );
function my_event_cpt() {
    $args = array(
      'public'       => true,
      'show_in_rest' => true,
      'label'        => 'Events'
    );
    register_post_type( 'event', $args );
}

Method 2:

add_action( 'init', 'my_custom_post_type_rest_support', 25 );

function my_custom_post_type_rest_support() {

    global $wp_post_types;

    //be sure to set this to the name of your post type!
    $post_type_name = 'book';

    if( isset( $wp_post_types[ $post_type_name ] ) ) {

        $wp_post_types[$post_type_name]->show_in_rest = true;
        // Optionally customize the rest_base or controller class
        $wp_post_types[$post_type_name]->rest_base = $post_type_name;
        $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';

    }

}

The second option is to use the register_post_type_args filter.

function sb_add_cpts_to_api( $args, $post_type ) {
    if ( 'book' === $post_type ) {
        $args['show_in_rest'] = true;
    }
    return $args;
}
add_filter( 'register_post_type_args', 'sb_add_cpts_to_api', 10, 2 );

Share this post: