"Back to Category" Link Above Products
Adds a "Back to Shoes" style link above each product page that returns the shopper to the product's main category.
Opens WPIDE on
Code
$product_id = get_the_ID();
$term_id = 0;
foreach ( array( '_yoast_wpseo_primary_product_cat', 'rank_math_primary_product_cat' ) as $meta_key ) {
$term_id = $term_id ? $term_id : (int) get_post_meta( $product_id, $meta_key, true );
}
$term = $term_id ? get_term( $term_id, 'product_cat' ) : null;
if ( ! $term || is_wp_error( $term ) ) {
$terms = get_the_terms( $product_id, 'product_cat' );
$term = $terms && ! is_wp_error( $terms ) ? $terms[0] : null;
}
if ( $term ) {
printf( '<p class="wpide-back-to-cat" style="margin:0 0 12px;"><a href="%1$s">← Back to %2$s</a></p>', esc_url( get_term_link( $term ) ), esc_html( $term->name ) );
}
Notes
Uses the product's first category, or the primary category set by Yoast SEO or Rank Math when available.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.