How do I get the rewrite slug of a custom post type inside a template?
register_post_type( 'products',
'rewrite' => array( 'slug' => 'fabrications' ),
// ... etc
);
Now inside my template file inside the global $post
there is post_type property. But I can't find the rewrite slug
anywhere.
Please help.
Update: I needed this for permalinks inside a template part where there are categories displayed.
<a href="<?php echo get_site_url() . '/' . $post_type_slug . '/category/' . $category->slug . '/' ?>" class="cat-bar__label"><?php echo $category->name; ?></a>
How do I get the rewrite slug of a custom post type inside a template?
register_post_type( 'products',
'rewrite' => array( 'slug' => 'fabrications' ),
// ... etc
);
Now inside my template file inside the global $post
there is post_type property. But I can't find the rewrite slug
anywhere.
Please help.
Update: I needed this for permalinks inside a template part where there are categories displayed.
<a href="<?php echo get_site_url() . '/' . $post_type_slug . '/category/' . $category->slug . '/' ?>" class="cat-bar__label"><?php echo $category->name; ?></a>
Share
Improve this question
edited Apr 14, 2020 at 10:03
Floris
asked Apr 14, 2020 at 9:49
FlorisFloris
3512 silver badges11 bronze badges
3
- I've posted a solution, but can I ask why? It's unusual to need this inside a template. – Jacob Peattie Commented Apr 14, 2020 at 9:58
- Sure. See update. – Floris Commented Apr 14, 2020 at 10:03
- See my updated answer. – Jacob Peattie Commented Apr 14, 2020 at 10:07
1 Answer
Reset to default 2You can access the post type properties using get_post_type_object()
. The rewrite argument will be a property if the returned object:
$post_type_object = get_post_type_object( 'products' );
$rewrite_slug = $post_type_object->rewrite['slug'];
Update
I needed this for permalinks inside a template part where there are categories displayed.
No you don't. To get the URL to a category archive, use get_term_link()
:
<a href="<?php echo esc_url( get_term_link( $category ) ); ?>" class="cat-bar__label"><?php echo $category->name; ?></a>