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. Apr 14 '20 at 9:58
  • Sure. See update.
    – Floris
    Apr 14 '20 at 10:03
  • See my updated answer. Apr 14 '20 at 10:07
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.
    – Floris
    Apr 14 '20 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
    – honk31
    Aug 31 '21 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.