How to Display the Primary Category for a Product or Post In WordPress Loop?
Jagdish Sarma Answered question June 4, 2020
Getting The Primary Category from a WooCommerce product
<?php //Grabs the Primary Category of the Product $primary_term_product_id = yoast_get_primary_term_id('product_cat'); $postProductTerm = get_term( $primary_term_product_id ); //If the post type is a product, display the Primary Category Link if ( 'product' === get_post_type() ) { ?> <div class=""> <?php if ( $postProductTerm && ! is_wp_error( $postProductTerm ) ) { echo '<a href="' . esc_url( get_term_link( $postProductTerm->term_id ) ) . $postProductTerm->slug . '">'; echo $postProductTerm->name; echo '</a>'; } ?> </div><?php }
Getting The Primary Category from a Post
<?php //Grabs the Primary Category of the Post $primary_term_id = yoast_get_primary_term_id('category'); $postTerm = get_term( $primary_term_id ); //If the post type is a post, display the Primary Category Link if( 'post' === get_post_type() ) { ?> <div class=""><?php the_time('m/j/Y'); ?> | <?php if ( $postTerm && ! is_wp_error( $postTerm ) ) { echo '<a href="' . esc_url( get_term_link( $postTerm->term_id ) ) . $postTerm->slug . '">'; echo $postTerm->name; echo '</a>'; } ?> </div> <?php }
Jagdish Sarma Answered question June 4, 2020