最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Get rewrite slug of custom post type in template

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 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>
发布评论

评论列表(0)

  1. 暂无评论