1

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> 
3
  • I've posted a solution, but can I ask why? It's unusual to need this inside a template. Commented Apr 14, 2020 at 9:58
  • Sure. See update. Commented Apr 14, 2020 at 10:03
  • See my updated answer. Commented Apr 14, 2020 at 10:07

1 Answer 1

2

You 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> 
2
  • Thank you, that is much better indeed. Commented Apr 14, 2020 at 10:13
  • Thanks for this, was looking for the first part of your answer. Regarding the second part just a little note: you can pass the term_id to get_term_link(), but if you do have the whole term object, use it. do not only pass the ID, since get_term_link() needs the object. it can work with the ID as well, but will use it, to get the object. and if you only have the ID, make sure to pass a number, since a string is considered a slug <3 Commented Aug 31, 2021 at 16:16

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.