Search code examples
phpwordpresswoocommercetagsproduct

Add specific info on single product page based on "Tag ID" in WooCommerce


In meta section of WooCommerce single product page, I need to extract one tag ID (135).

I want to look at all the tags that are in a simple product, and if I come across a tag with ID 135 to print:

  • Material: Leather (ID 135)

I was trying something, but I can't get to that tag ID

add_action('woocommerce_product_meta_end', 'wh_renderProductTagDetails');

function wh_renderProductTagDetails()
{
    global $product;
    $tags = get_the_terms($product->get_id(), 'product_tag');
    //print_r($tags);
    if (empty($tags))
        return;
    foreach ($tags as $tag_detail)
    {
        
        if ($tags (135)){
        
        // echo '<p> Material: Leather</p>'; 
       echo '<p> Material: ' . $tag_detail->name . '</p>'; 
        }
    }
}

Can someone walk me through how to do that?


Solution

  • Your code contains some minor bugs.

    This should suffice - explanation via comment tags added in the code.

    function action_woocommerce_product_meta_end() {
        global $product;
        
        // Is a WC product
        if ( is_a( $product, 'WC_Product' ) ) {
            // Set taxonmy
            $taxonomy = 'product_tag';
            
            // Get the terms
            $terms = get_the_terms( $product->get_id(), $taxonomy );
            
            // Error or empty
            if ( is_wp_error( $terms ) ) {
                return $terms;
            }
    
            if ( empty( $terms ) ) {
                return false;
            }
            
            // Loop trough
            foreach ( $terms as $index => $term ) {
                // Product tag Id
                $term_id = $term->term_id;
                
                // DEBUG: remove afterwards
                echo '<p>DEBUG - Term id: ' . $term_id . '</p>';
                
                // Compare
                if ( $term_id == 135 ) {
                    echo '<p>Material: ' . $term->name . '</p>'; 
                }
            }
        }
    }
    add_action( 'woocommerce_product_meta_end', 'action_woocommerce_product_meta_end', 10, 0 );