0

I have a WP_Query class on the home page of a site that pulls in a custom post type, and as part of this I want to show the custom taxonomy (category) for this post type.

The solution I currently have pulls the taxonomy name in, but doesn't include the hyperlink? I would like it so when a user clicks this custom taxonomy it shows the related archive page for this taxonomy.

The specific snippet of code I'm using on the page in relation to the taxonomy is:

<p class="cat">
    <?php  $terms = get_the_terms( $post->ID, 'news_categories' );
            foreach ( $terms as $term ) {
            echo $term->name;
            }
    ?>
</p>

And the above snippet is part of this larger code block:

<?php 
    $homePageNews = new WP_Query(array(
        'posts_per_page' => 3,
        'post_type'=> 'news'
    ));

    while(  $homePageNews->have_posts()){
            $homePageNews->the_post(); ?>

            <article class="article top-article lastest-news-article">
            <a href="<?php the_permalink(); ?>">
            <?php the_post_thumbnail('post-thumbnail', 
                ['class' => 'image latest-top-image hover-class']); ?>
            </a>   
                <p class="cat">
                    <?php  $terms = get_the_terms( $post->ID, 'news_categories' );
                            foreach ( $terms as $term ) {
                            echo $term->name;
                            }
                    ?> <a href=""></a>
                </p>
                <div class="content-wrapper content-wrapper-mobile-padding">
                    <h3 class="td no-bottom-margin hover-class"><a title="<?php the_title(); ?>" class="td top-latest-heading" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <hr>
                    <p><?php the_content(); ?></h3></p>
                </div>
            </article>

<?php } ?>

<?php  wp_reset_postdata(); ?>

1 Answer 1

2

@Chewy you can try below code snippet.

<p class="cat">
    <?php
    $terms = get_the_terms($post->ID, 'news_categories');
    foreach ($terms as $term) {
        $term_id    = $term->term_id;
        $term_name  = $term->name;
        $term_link  = get_term_link( $term_id );
        echo "<a href='".$term_link."'>".$term_name."</a>";
    }
    ?> 
</p>

please chcek and let me know if this work or not.

if not then please ping me I will definitely help you.

Thanks.

1
  • Hi @DipPatel That worked. Thank you so much. Really appreciated !
    – pjk_ok
    Commented Jan 30, 2020 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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