Вопрос

I'm writing a small plugin to add some text above the 'Add To Cart' button on the WooCommerce product page.

My code:

add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
function ddd_above_add_to_cart() { 
    if(is_product_category('vss') ) {
        echo 'hello world';
        }
}

My problem is when I use the conditional tag is_product_category('vss') to display the text based on the product category. I'm sure this error is occurring as the function is not running inside the loop, but I'm not sure how to change this.

Can anyone help me with this?

Это было полезно?

Решение

Thist function not working in product page

is_product_category()

So, for me the best options is first get the terms of the current post and the next step is get the name or slug, in this case i chose the category name

$product_cat_name = $term->name;

But you can chose the slug too (better option)

$product_cat_slug = $term->slug; 

Here the documentation https://developer.wordpress.org/reference/functions/get_the_terms/

Example for Category name

/*Write here your own functions */
    add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
    function ddd_above_add_to_cart() { 

            global $post;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            $nterms = get_the_terms( $post->ID, 'product_tag'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                break;
            }      
           //compare current category name == any category name you want
            if($product_cat_name =='vss' ) {
                echo "This Work";
            }           
    }

Example for Category Slug

/*Write here your own functions */
    add_action('woocommerce_before_add_to_cart_button', 'ddd_above_add_to_cart', 100);
    function ddd_above_add_to_cart() { 

            global $post;
            $terms = get_the_terms( $post->ID, 'product_cat' );
            $nterms = get_the_terms( $post->ID, 'product_tag'  );
            foreach ($terms  as $term  ) {
                $product_cat_id = $term->term_id;
                $product_cat_name = $term->name;
                $product_cat_slug = $term->slug;
                break;
            }      

            //compare current category slug == any category slug you want
            if($product_cat_slug =='any-slug-category' ) {
                echo "This Work";
            }           
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top