[英]Link to custom post type category
Hello I've made custom post type and add categories(taxonomies) to this. 您好,我已经制作了自定义帖子类型,并为此添加了类别(分类法)。 So I have custom post type called portfolio with a few categories for example: websites, logo, etc. and I want to get link to this categories.
因此,我有一个称为投资组合的自定义帖子类型,其中有一些类别,例如:网站,徽标等,我想获得此类别的链接。 I tried like this:
我这样尝试过:
<?php
// Get the ID of a given category
$category_id = get_cat_ID( 'Website' );
$id = get_term_by('name', 'Website', 'portfolio_category');
// Get the URL of this category
$category_link = get_category_link( $category_id );
?>
But it doesn't work. 但这是行不通的。 How can I get the link to this custom post type categories.
如何获得此自定义帖子类型类别的链接。
I believe you can use WordPress's get_term_link()
as below: 我相信您可以使用WordPress的
get_term_link()
如下:
$terms = wp_get_post_terms( $post->ID, 'category');
foreach ($terms as $term) :
echo '<a href="'.get_term_link($term->slug, 'category').'">'.$term->name.'</a>';
endforeach;
you need to alter category queries via pre_get_posts for custom post type. 您需要通过pre_get_posts更改自定义帖子类型的类别查询。
function wpa_cpt_in_categories( $query ){
if ( ! is_admin()
&& $query->is_category()
&& $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'portfolio' ) );
}
}
add_action( 'pre_get_posts', 'wpa_cpt_in_categories' );
You can also refer get_term_link from here 您也可以从此处引用get_term_link
$terms = get_terms('Website');
echo '<ul>';
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term->slug, 'Website').'">'.$term->name.'</a></li>';
}
echo '</ul>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.