phphtmlwordpresswoocommercetaxonomy-terms

How to get WooCommerce product category url to display it in HTML meta tag?


Below I am able to display the product permalink when it's a single product page, but I want to do the same for a product category archive pages.

Here is my code:

<meta name="twitter:url" content="<?php
if( is_product_category() ){
   $cat_link = get_category_link($category->cat_ID);
   echo $category; // category link
} else
the_permalink(); ?>" />

What I get is an empty echo for product category archives.

How to get WooCommerce product category url to display it in HTML meta tag?


Solution

  • For WooCommerce product category (custom taxonomy) use WordPress get_term_link() function like:

    <meta name="twitter:url" content="<?php
    if( is_product_category() ){
        $term_link = get_term_link(get_queried_object_id(), 'product_cat');
        if ( ! is_wp_error( $term_link ) ) {
            echo $term_link;
        }
    } else {
        the_permalink(); 
    } ?>" />
    

    It should work.