Change name of custom post type archive
-
11-01-2021 - |
Question
I have a custom post type acme_reviews
. I've namespaced it as suggested in tutorials to prevent future conflicts. But I want its archive page to simply be acme.com/reviews
, not acme.com/acme_reviews
. How do I achieve this? This is my code:
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type');
Solution
The register_post_type has_archive option also accepts a string. That string will be used for the archives. See the changes in the code below:
function create_reviews_post_type() {
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => 'reviews',
);
}
add_action('init', 'create_reviews_post_type');
OTHER TIPS
According to the codex (and what works for me!) is to just use a rewrite in the array. Both options work but wordpress suggests using the rewrite Below is the quote directly from the codex:
has_archive (boolean or string) (optional) Enables post type archives. Will use $post_type as archive slug by default.
Default: false
Note: Will generate the proper rewrite rules if rewrite is enabled. Also use rewrite to change the slug used.
MAKE SURE TO FLUSH THE PERMALINK RULES. if this is in a plugin i always suggest adding an init that flushes the rules when the plugin is activated.
Here is the code, notice i customized the function name too for the same reasons that you customize the post name itself.
function create_acme_reviews_post_type() { //namespaced your function too..
register_post_type('acme_reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'menu_position' => 5,
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'reviews' ), //changes permalink structure
)
);
}
add_action('init', 'create_acme_reviews_post_type'); //namespaced function call too..