skip to Main Content

I’m trying to show custom text for products in a specific woo commerce category.
This is the code I added to function.php , but it shows the text in the category page not the products page.

add_action( 'woocommerce_after_main_content', 'add_my_text' );
function add_my_text() {
    if ( is_product_category( 'category1' ) ) {
        echo '<p>This is my extra text.</p>';
    }    
}

p.s. is it any good to add “if (function_exists(add_action))” at the beginning?

2

Answers


  1. Chosen as BEST ANSWER

    this works:

    add_action( 'woocommerce_after_single_product_summary', 'add_text' );
    
    function add_text() {
    
    if ( has_term( 'nail', 'product_cat' ) ) {
    echo 'Something';
    } elseif ( has_term( 'tables', 'product_cat' ) ) {
    echo 'Something else';
    }
    
    }
    

  2. To show the text in the Product page of this particular category, you should add the conditional Tag is_product() and check it has the right category with the has_term() function like this:

    add_action( 'woocommerce_after_main_content', 'add_my_text' );
    function add_my_text() {
        //1st grab the product/post object for the current page if you don't already have it:
        global $post;
        //2nd you can get the product category term objects (the categories) for the product
        $terms = wp_get_post_terms( $post->ID, 'product_cat' );
        foreach ( $terms as $term ) $categories[] = $term->slug;
        //Then we just have to check whether a category is in the list:
        if ( is_product_category( 'category1' ) || is_product() && in_array( 'category1', $categories ) ) {
            echo '<p>This is my extra text.</p>';
        }    
    }
    

    And for the if (function_exists(... question, it’s for a matter of backward compatibility as mentionned in this answer : https://wordpress.stackexchange.com/a/111318/136456

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search