• Resolved dmarchetti

    (@dmarchetti)


    Hi everyone, I need help here in my functions.php …

    I need to show text for each different product category before the quantity in the product part as shown in the image below:

    Image

    In case if it is the category “floors” needs to show the text “Box:” because the products are sold in boxes.

    If it is the category “footers” you need to show “Ruler:” because the products are sold in rulers.

    If it is the category “lamps” it needs to show “Unit:” because the bulbs are sold in units.

    I created an if, else here but I realize that it is only showing the else (Drive 🙂 on the site …

    Here is the code below that is in functions.php:

    add_action ('woocommerce_before_add_to_cart_quantity', 'text_qtd_boxes', 20);
    
    function text_qtd_boxes () {
    
    if (is_product_category ('floor-tiles')) {
    echo '<h3> Boxes: </ h3>';
    }
    elseif (is_product_category (array ('rodapes'))) {
    echo '<h3> Rulers: </ h3>';
    }
    else {
    echo '<h3> Unit (s): </ h3>';
    }
    
    }

    There is something wrong there that I do not know what it is … I think I’m not able to filter the categories correctly so it’s just showing the other …

    I tried collecting the categories by id too and I could not …

    Wordpress version 4.9.8 with Flatsome theme (Child) and Woocommerce.

    Someone help?

    Thanks in advance!

    • This topic was modified 6 years, 6 months ago by dmarchetti.
Viewing 2 replies - 1 through 2 (of 2 total)
  • is_product_category ('floor-tiles') does not tell you if a product has that category, it tells you if you are browsing that category. So if the URL is like /product-category/floor-tiles/.

    If you want to check if a product has a category, you need to use the has_term() function, with the global $product variable’s ID:

    function text_qtd_boxes () {
    	global $product;
    	
    	if ( has_term( 'floor-tiles', 'product_cat', $product->get_id() ) ) {
    		echo '<h3> Boxes: </ h3>';
    	}
    	elseif ( has_term( 'rodapes', 'product_cat', $product->get_id() ) ) {
    		echo '<h3> Rulers: </ h3>';
    	}
    	else {
    		echo '<h3> Unit (s): </ h3>';
    	}
    }
    
    Thread Starter dmarchetti

    (@dmarchetti)

    Thanks @jakept !

    Works like a charm!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Category filter and show string with IF, ELSE on functions.php’ is closed to new replies.