0
votes

I use the following code to register the "media" post type.

function cw_post_type() {

    register_post_type( 'media',
        // WordPress CPT Options Start
        array(
            'labels' => array(
                'name' => __( 'Media' ),
                'singular_name' => __( 'Media' )
            ),
            'has_archive' => true,
            'public' => true,
            'rewrite' => array('slug' => 'media'),
            'show_in_rest' => true,
            'supports' => array('editor', 'title')
        )
    );
}

add_action( 'init', 'cw_post_type' );

But this will show me a blank page.

I found that a request to /index.php?rest_route=/wp/v2/media/6&context=edit&_locale=user got a 404 with the following response.

{
  "code": "rest_post_invalid_id",
  "message": "Invalid post ID.",
  "data": {
    "status": 404
  }
}

If I set the 'show_in_rest' to false, it works, but that way the gutenberg editor won't shown up.

And if I changed the custom post type name 'media' to any other name, it works again.

Anyone know how to solve this problem?

By the way, I've tried this on a fresh installation of WordPress with it's default theme with out any plugins enabled.

1
The term "media" may not be allowed in WordPress to use as a custom post type. Have you tried adding a prefix or suffix to the "media"? Try with "my-custom-media" or similar terms.DebRaj

1 Answers

0
votes

The term media is a reserved term and cannot be used for registering a custom post type or post type slug. In your Custom Post Type, the 'rewrite' => array('slug' => 'media') conflicts with the WordPress core media type and causes the 404 error described. Also, using a reserved term creates a conflict in the REST API and query vars.

There is a complete list of reserved terms in the Codex: https://codex.wordpress.org/Reserved_Terms

Best practise is to prefix your Custom Post Type with a unique identifier, eg

function cw_post_type() {

    register_post_type( 'cw_media', // Must be unique and not conflict with WordPress Core
        // WordPress CPT Options Start
        array(
            'labels' => array(
                'name' => __( 'CW Media' ),
                'singular_name' => __( 'CW Media' )
             ),
            'has_archive' => true,
            'public' => true,
            'rewrite' => array('slug' => 'cw_media'), // Cannot be a reserved term
            'show_in_rest' => true,
            'supports' => array('editor', 'title')
        )
    );
}

add_action( 'init', 'cw_post_type' );