链接到自定义帖子类型类别


Link to custom post type category

你好,我已经自定义了帖子类型并添加了类别(分类法)。所以我有自定义的帖子类型称为投资组合与几个类别,例如:网站,标志等,我想得到链接到这个类别。我试过这样做:

<?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 );
?> 

但是它不起作用。我怎么能得到链接到这个自定义的帖子类型类别。

我相信你可以使用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;

您需要通过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' );

你也可以从这里引用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>';