Halloween Sale 15% off Ends in See the plans
PHP

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

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.