简体   繁体   中英

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:

$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.

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

$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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM