WooCommerce Conditional Logic – Tags, Examples & PHP

The WooCommerce and WordPress conditional tags (“WooCommerce and WordPress Conditional Logic”) can be used in your functions.php to display content based on certain conditions. For example, you could display different content for different categories within a single PHP function.

You can find the list of WooCommerce conditional tags here and WordPress conditional tags here. I don’t think it’s worth it to paste them here, so please use those two links as a reference – in fact in this blog post I would like to give you EXAMPLES, probably the best way for you to learn WooCommerce customization.

First: How to Use Conditional Logic

You may have a PHP snippet (any of the ones you find on this website for example), that does something like this:

add_action( 'woocommerce_before_single_product', 'bbloomer_echo_text' ); 

function bbloomer_echo_text() { 
   echo 'SOME TEXT'; 
} 

As you can see, this prints some text on top of the single product page. Conditional logic means that you want to run the function ONLY given a certain condition, for example in this case we want to print that text ONLY if the product ID is 25.

The way you need to modify the above function is therefore by “wrapping” the whole inside of the function inside a conditional check: if it’s product 25 do this, if not do nothing.

The function will therefore become:

add_action( 'woocommerce_before_single_product', 'bbloomer_echo_text' );

function bbloomer_echo_text() {
   global $product;
   if ( 25 === $product->get_id() ) {
      echo 'SOME TEXT';
   }
}

As you can see, the “echo” only happens if the condition is true. Now, keep reading for more conditional logic examples!

1. Are you working on the WooCommerce Single Product Page?

Great thing about single product pages in WooCommerce is that WordPress knows they are “posts”. So, you can use is_single. The list of hooks for the single product page can be found here.

PHP: do something on single product pages only

add_action( 'woocommerce_before_main_content', 'bbloomer_single_product_pages' );

function bbloomer_single_product_pages() {

if ( is_product() ) {
echo 'Something';
} else {
echo 'Something else';
}

}

PHP: do something if product ID = XYZ

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_product_ID' );

function bbloomer_single_product_ID() {

if ( is_single( '17' ) ) {
echo 'Something';
} elseif ( is_single( '56' ) ) {
echo 'Something else';
}

}

PHP: do something if product belongs to a category

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_category_slug' );

function bbloomer_single_category_slug() {

if ( has_term( 'chairs', 'product_cat' ) ) {
echo 'Something';
} elseif ( has_term( 'tables', 'product_cat' ) ) {
echo 'Something else';
}

}

PHP: do something if product belongs to a tag

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_tag_slug' );

function bbloomer_single_tag_slug() {

if ( has_term( 'blue', 'product_tag' ) ) {
echo 'Something';
} elseif ( has_term( 'red', 'product_tag' ) ) {
echo 'Something else';
}

}

PHP: do something if product is on sale

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_on_sale' );

function bbloomer_single_on_sale() {
global $product;
if ( $product->is_on_sale() ) {
 // do something
}

}

PHP: do something if product is simple, variable, external…

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_product_type' );

function bbloomer_single_product_type() {
global $product;
if( $product->is_type( 'simple' ) ){
 // do something
} elseif( $product->is_type( 'variable' ) ){
 // do something
} elseif( $product->is_type( 'external' ) ){
 // do something
} elseif( $product->is_type( 'grouped' ) ){
 // do something
} 

}

PHP: do something if product is virtual

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_virtual' );

function bbloomer_single_virtual() {
global $product;
if( $product->is_virtual() ){
 // do something
} 

}

PHP: do something if product is downloadable

add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_downloadable' );

function bbloomer_single_downloadable() {
global $product;
if ( $product->is_downloadable() ){
 // do something
} 

}

PHP: do something on the related products only

Related products are generated by a “loop”. Sometimes you might want to use your PHP on the single product page only (and excluding the related ones) or viceversa.

The snippet below hides the price only on the single product page and only on the related products section.

add_filter( 'woocommerce_variable_price_html', 'bbloomer_remove_variation_price', 10, 2 );

function bbloomer_remove_variation_price( $price ) {

global $woocommerce_loop;

if ( is_product() && $woocommerce_loop['name'] == 'related' ) {
$price = '';
}

return $price;
}

2. Are you working on the WooCommerce Shop/Category Page?

You can find all the shop/archive WooCommerce hooks here. Let’s see how to use conditional logic on these “loop” pages:

PHP: do something on the Shop page only

add_action( 'woocommerce_before_main_content', 'bbloomer_loop_shop' );

function bbloomer_loop_shop() {

if ( is_shop() ) {
echo 'This will show on the Shop page';
} else {
echo 'This will show on all other Woo pages';
}

}

PHP: do something on each product on the loop pages

add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_loop_per_product' );

function bbloomer_loop_per_product() {

if ( has_term( 'chairs', 'product_cat' ) ) {
echo 'Great chairs!';
} elseif ( has_term( 'tables', 'product_cat' ) ) {
echo 'Awesome tables!';
}

PHP: do something on category pages only

add_action( 'woocommerce_before_main_content', 'bbloomer_loop_cat' );

function bbloomer_loop_cat() {

if ( is_product_category() ) {
echo 'This will show on every Cat pages';
} else {
echo 'This will show on all other Woo pages';
}

}

PHP: do something based on category name

add_action( 'woocommerce_before_main_content', 'bbloomer_loop_cat_slug' );

function bbloomer_loop_cat_slug() {

if ( is_product_category( 'books' ) ) {
echo 'This will show on the Books Cat page';
} elseif ( is_product_category( 'chairs' ) ) {
echo 'This will show on the Chairs Cat page';
}

}

PHP: do something on tag pages only

add_action( 'woocommerce_before_main_content', 'bbloomer_loop_tag' );

function bbloomer_loop_tag() {

if ( is_product_tag() ) {
echo 'This will show on every Cat pages';
} else {
echo 'This will show on all other Woo pages';
}

}

PHP: do something based on tag name

add_action( 'woocommerce_before_main_content', 'bbloomer_loop_tag_slug' );

function bbloomer_loop_tag_slug() {

if ( is_product_tag( 'red' ) ) {
echo 'This will show on the Red Tag page';
} elseif ( is_product_tag( 'yellow' ) ) {
echo 'This will show on the Yellow Tag page';
}

}

3. Are you working on WooCommerce Pages?

PHP: do something if on a WooCommerce page (excluding cart/checkout e.g. shop & cats & tags & products)

add_action( 'woocommerce_before_main_content', 'bbloomer_woo_page' );

function bbloomer_woo_page() {
   if ( is_woocommerce() ) {
      echo 'This will show on Woo pages';
   } else {
      echo 'This will show on WP pages';
   }
}

PHP: do something if on Cart/Checkout

add_action( 'woocommerce_sidebar', 'bbloomer_cart_checkout' );

function bbloomer_cart_checkout() {
   if ( is_cart() ) {
      echo 'This will show on the Cart sidebar';
   } elseif ( is_checkout() ) {
      echo 'This will show on the Checkout sidebar';
   }
}

PHP: do something if on Checkout Order Pay page

add_action( 'hook', 'bbloomer_orderpay' );

function bbloomer_orderpay() {
   if ( is_checkout_pay_page() ) {
      echo 'This will show on Order Pay page';
   } else {
      echo 'This will show on all other pages';
   }
}

PHP: do something if on My Account pages

add_action( 'hook', 'bbloomer_myaccount' );

function bbloomer_myaccount() {
   if ( is_account_page() ) {
      echo 'This will show on My Account pages';
   } else {
      echo 'This will show on pages different than My Account';
   }
}

PHP: do something if on Thank You Page

You could easily run functions on the thank you page by using the woocommerce_thankyou hook:

add_action( 'woocommerce_thankyou', 'bbloomer_run_function_thankyou_page' );
 
function bbloomer_run_function_thankyou_page() {
   // whatever
}

Otherwise, you can use another conditional, so that you know you’re on the “thank you page endpoint”:

add_action( 'wp_head', 'bbloomer_run_function_thankyoupage' );

function bbloomer_run_function_thankyoupage() {
   if ( is_wc_endpoint_url( 'order-received' ) {
      // whatever
   }
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]
  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

117 thoughts on “WooCommerce Conditional Logic – Tags, Examples & PHP

  1. Hello,

    Is there a way to showcase the conditional text on woo-commerce pages that matches particular names irrespective of whether it is a category or tag or shop page?

    Let me know

    Thanks.

    1. Sure! You wish to target the URL or the page title?

  2. Hey Rodolfo,

    How would we remove a product title on a specific product ID?

    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );

    But how to use conditional logic for when removing?

    Thanks.

    1. Solved by using the following

      function action_woocommerce_single_product_summary() {
          global $product;
          
          // Set Id's
          $product_ids = array ( 30, 815 );
          
          // Is a WC product
          if ( is_a( $product, 'WC_Product' ) ) {
              // Get productID
              $product_id = $product->get_id();
              
              // Product Id is in the array
              if ( in_array( $product_id, $product_ids ) ) {
                  // Remobe
                  remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
              }
          }
      }
      add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 4 );
  3. Thanks for useful code snippet. I want to do something based on product attribute. Then, Show me some example of code.

    1. Have you tried anything yet?

  4. Hi Rodolfo, is there a conditional snippet for when a product is in stock or out of stock. I need to add a category or tag to products based on that condition.

    1. Hey Gina, sure!

      if ( $product->is_in_stock() ) { 
  5. Thanks for the tutorials. They are helping point me in the right direction. I am using Blocksy Theme which has a custom filter “blocksy:general:sidebar-position” with options of none/left/right. I ma trying to remove the sidebar space on certain product categories. The problem is when I use the following code I remove the sidebar from all product categories.

    add_filter('blocksy:general:sidebar-position', function () {
    if (is_product_category ( 'bench pads' ))	
      return 'none';
    });
    1. Hi Brian, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom troubleshooting work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  6. Hi,

    I’ve added a custom function to show the artist name. But is should only show for certain type of products (e.g. categories).
    When I use the function for all products it works fine, but with IF function it does not show.

    function sp_artist_name() {
    	
    	if ( is_product_category( 'digital'  , '12inch-vinyl) ) {
        echo "<div class='product-display-artist-name'>";
    	echo 'By: ' . get_field('sp_artist_name');
    	echo "</div>";
    	}
    }
    
    1. You can only check for one category at once

  7. I was watching Joshua Michaels’ youtube video. He shared your links for woocommerce hooks. I want to ask something. The developer is adding a div wrapper with a condition via if statement. Can we get the product price and use it in if statement and then use echo to display a div on a product page. We can use if for categories for instance. However, let’s say a data (a picture or any text) can be seen if the price of the product as data can be accessed. Is there any way to get that price value and use it in if statement.

    1. Hi Kenan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  8. Hello,

    if I want to hide products of a specific category?

  9. Hi
    I’m trying to create a solution for the following
    Just need some help to see if something like this is possible somehow

    I need to use the sum of the quantity of all cart items to create button or page link options. So if cart quantity sum was 1 then this would conditionally display a button that I could add a custom link to. Similarly, if the quantity sum was 2. 3 or 4plus then a button for each of these would conditionally show. The purpose is to avoid having to display all four buttons (eliminating the ability to click the wrong button) and so only display the relevant button determined automatically by the cart quantity sum.

    Hope this makes sense 🙂

    1. Hi Danny, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  10. Hey Rodolfo your site is amazing!!! Thank you so much for all those code snippets!
    What I am trying to do is a page showing products of a particular category using short-code.
    Now I want to remove the thumbnails from those products.
    But if I use your code

    add_action( 'woocommerce_before_main_content', 'bbloomer_loop_cat_slug' );
     
    function bbloomer_loop_cat_slug() {
     
    if ( is_product_category( 'stc' ) ) {
    echo 'This will show on the Books Cat page';
    } elseif ( is_product_category( 'chairs' ) ) {
    echo 'This will show on the Chairs Cat page';
    }
     
    }
    

    It shows on the category page itself only… Any hint?

    1. Thanks Daniela, is_product_category() will only work on category pages

  11. Hello,

    How to check if the current category page (front page) doesn’t have any subcategories? I don’t want to hard code the category name in the

    is_product_category('category name')

    function.

    All my categories and subcategories are displaying subcategories unless there are none and then the products grid is displayed. And I want to target all these subcategories which don’t have any subcategories in them but only the products themselves.

    Will really appreciate the help.

    1. Hi Victor, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  12. Hello! First of all good for the article.
    I have a question, when I add a product to the cart a cross sell appears with suggested products, but when I delete that product and empty the cart, only the “Back to shop” button remains. I wish that even when the cart is empty, there must be some suggested products. Is there any way to do this?

    1. Hi Gianluigi, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  13. Hi,
    This snippet is not working for me.

    add_action( 'woocommerce_before_main_content', 'bbloomer_loop_cat_slug' );
     
    function bbloomer_loop_cat_slug() {
     
    if ( is_product_category( 'copii' ) ) {
    echo 'This will show on the Books Cat page';
    } elseif ( is_product_category( 'femei' ) ) {
    echo 'This will show on the Chairs Cat page';
    }
     
    } 
    1. Does it work with 2020 theme?

  14. Aweosme info here.

    Is there a way to search if a product attribute has a certain value and then echo a particular text/image

    something like

    if product attribute colour is set as red
    then echo ‘some img url’
    or if product attribute colour is set as blue
    then echo ‘some img url’
    …..

    Thanks.

    1. Dheeraj, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  15. its great that there is some custom conditions here but the question is where should we place this for an existing php snippet?i know that we cant just past it below or someone around the existing code. can you please make it more understandable for us?

    1. Good point, let me see if I can add an intro

  16. Hey Rodolfo,

    first let me say: cool site!

    Perhaps you can help me. I´d like to add a conditional logic field for a gun shop into the backend at the product creation step.

    Example:

    if i create a product i want to set a hidden attribute “authorization needed”
    If this attribute is set, a text field should be shown on product frontend saying you need to attach your buying authorization with the possibility to upload a authorization file that will be attached to the order.

    Another possibility would be to set authorization in the backend menu and show a info & upload tab in the checkout fields.

    How can i handle this?

    Best
    Chris

    1. Hi Chris, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  17. Hi thank you so much for this awesome guide!!
    Is there a way to know the category name?
    I’m trying to add a Badge on products archive page (and I read all your other posts about it)
    but my category names are in Hebrew, and it’s seems like nothing is changing.
    Should I use the slug? or the ID of the category?

    1. In your case maybe the ID should work better. Let me know

  18. Is there a way to conditionally hide/show billing fields based on if the cart total is >$0? When there’s a 100% off coupon, I don’t want to require users to enter billing info.
    Thanks in advance,
    Daniel

    1. Hi Daniel, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  19. Thanks for the great list of conditionals! Very helpful!

    I’m looking to put some conditional tags to customize the email templates. For example, we want each email to get its own header image, which is the email-header.php. So, if “email A”, then “email A image header”, etc.

    Can that be done? Any direction you can point me?

    Thanks again for a great post.

  20. Hi Rodolfo,
    I just came across this page whilst trying to make my website do something with PHP. I’ve taken bits from various tutorials and cant get any of it to work.

    I have a Product which has a variation to be purchased as either a VIRTUAL PRODUCT or PHYSICAL PRODUCT.
    If a Physical product is purchased – a Gift card div #checkout_Add_ons appears on the checkout page.
    BUT if ONLY a “VIRTUAL” product is in the cart I’d like the div #checkout_Add_ons to be hidden.

    I think in PHP I should be able to write if ONLY a VIRTUAL PRODUCT is in card – change class of #checkout_Add_ons to none.
    But I can’t seem to work it out. Any suggestions greatly appreciated.

    Kind regards,
    Eoin

    1. Hiya Eoin, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  21. Hi, I want to hide the price if the product belongs to a specific tag (for example, test). From what I see I will need to use this code:

    add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_tag_slug' );
     
    function bbloomer_single_tag_slug() {
     
    if ( has_term( 'test', 'product_tag' ) ) {
    echo 'Something';
    } elseif ( has_term( 'red', 'product_tag' ) ) {
    echo 'Something else';
    }
     
    }
    

    What should I change in the code so it will simply hide the price for the products under the test tag?

    Thanks!

    1. Hi Drod – you’ll need a conditional “remove_action”. See which one is the “add_action” that prints prices, then instead set that to “remove_action”. finally, if that works (should hide all prices), wrap it in between a conditional to only run that for products that belong to your tag. Hope this helps

      1. Hi ,I need help adding (two buttons with different options)to a variable product where conditional logic can be applied and some of the variations should be visible only if button 1 is pressed and some of the variations should be visible only if button 2 Is pressed.

        1. Neha, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  22. Hi Rodolfo,

    I’ve managed to conditionally hide specific billing and other fields when the total cart value is zero. Now when a payable upsell is added on this checkout page, the order review field is updated automatically and it is also recalculated showing the correct amount to be paid i.e. total cart value 0. Unfortunately the conditionally hidden billing fields remain hidden even when the total cart value is now not zero anymore. Refreshing the page does not solve this issue.

    When I go back to the shopping cart page, and then move on to the checkout page (without changing the content of the cart), the billing fields are visible again.

    IMHO the total cart value in my code snippet is not updated when the upsell is added and the cart value is automatically recalculated.
    I hope that you (or someone else) has a simple and elegant solution to solve this issue.

    I’m using global $woocommerce and if ( $woocommerce->cart->total != 0 ) condition.

    Looking forward to your reply, and many thanks for your great Woo knowledge sharing !

    1. Hi Casper, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  23. Could you give one example that how to exclude sale products on specific product category?

    1. Hi Ashok, thanks so much for your comment! I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  24. Hi,

    Looking for assistance in writing a hook/function that looks at the product tag and appends text to the end of the price based on different tags. I found your example of targeting tags and another example of text after price but not sure how to blend them together with the elseif statements. If you end with any time, a tutorial on how to blend 2 functions together like below to get a result would be great.

    add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_tag_slug' );
    function bbloomer_single_tag_slug() {
    if ( has_term( 'blue', 'product_tag' ) ) {
    echo 'Something';
    } elseif ( has_term( 'red', 'product_tag' ) ) {
    echo 'Something else';
    }
    }
    ----
    function cw_change_product_price_display( $price ) {
    $price .= ' per 1/2 yard ';
    return $price;
    }
    add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
    add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
    
    1. Hi Ryan, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  25. Hi there, this page is amazing! I found a great help already but I will ask for a little more.
    I try to hide add to cart button if the product is virtual. Seems not to work, but I can echo easily.

    /*REMOVE ADD TO CART FOR VIRTUAL PRODUCT*/
    add_action( 'woocommerce_before_add_to_cart_button', 'remove_add_to_cart_button', 1 );
    
    function remove_add_to_cart_button() {
    global $product;
    	 	if( $product->is_virtual() )
    		{
    echo '<h6>Virtual Product</h6>';
    	 remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
           remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
           remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
           remove_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );
           remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
           remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
    } 
     
    }
    
    

    Thank you already!

    1. Hey Louis. Your code is a bit messy i.e. to remove actions you need to hook into “init” or “wp” and not “woocommerce_before_add_to_cart_button”

  26. Hello Rodolfo,

    Using Snippet 4. I managed to display some text depending on the product in the cart.

    add_action('woocommerce_before_cart', 'bbloomer_find_id_in_cart', 10);
    function bbloomer_find_id_in_cart() {
    global $woocommerce;     
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
        $product = $values['data'];
        if ( $product->id == 28088 ) {
            echo 'Add some text before cart';
        }   
    }
    }
    

    I would like to know if the “// do something” in your Snippet 4. could also be a text replacement in the spirit of your other snippet hereuncer and if so how to do it.

    add_filter( 'gettext', 'bbloomer_translate_woocommerce_strings', 999 );
    function bbloomer_translate_woocommerce_strings( $translated ) {
    $translated = str_ireplace( 'Initial text', 'Replacement text', $translated );
    return $translated;
    }
    

    My attempts building from what I did with the woocommerce_before_cart hook have not been fruitful.

    Thanks for your help,

    Nicolas

    1. Hi Nicolas, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  27. Hey,
    This is awesome. But for a newbie a bit complicated. I’m just studying these stuff.
    How would it look if I wanted to add a “Request a Quote” button with a CF7 on specific categories. I understand that conditional logic would be the category part, but then I’m… lost. I read both your posts, where you explain the snippet for the contact form on the product page. What I don’t get is how to put that snippet “inside” the conditional of being on certain category.
    Example:
    If selected a product (single product page) from the category “Chairs”, there’s no price, but “Request Quote” button leading to a CF7.
    Would be great if you could spare ]a few minutes to put it together.
    Thank you so much for sharing your knowledge.

    1. Hello Alex, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  28. Hello Rodolfo –

    At first, a big “THANK YOU” for this great article. It helped me a lot to understand a little more of these php-actions, though I’m a WP-newbie. Unfortunately I wasn’t able to solve my problem, of creating a php-snippet that hides the banner and the title ONLY on the Shop-categories- and subcategories-pages, WITHOUT hiding them on the Shop-Starting-page.

    Although this code-example from above, works successfully

    add_action( 'woocommerce_before_main_content', 'bbloomer_loop_cat' );
     
    function bbloomer_loop_cat() {
    if ( is_product_category( 'segel' ) ) {
    echo 'This will show on the Segel Cat page';
    } else {
    echo 'This will show on all other Woo pages';
    }
    }
    
    

    And though I’ve found this code that effectively hides the banner and title on EACH Woocommerce page,

    add_filter( 'woocommerce_show_page_title', '__return_false' );

    I’m constantly failing to combine these 2 codes. I guess I have tried dozens of combinations but nothing seems to work. Therefore I desperately need some support and would appreciate any help.

    With kind regards
    Reca

    1. Hello Reca, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  29. I’m using your code to remove a wishlist button from up sell products as follows

    function ssheds_remove_upsell_wishlist() {
    global $woocommerce_loop;
    if ( is_product() && $woocommerce_loop['name'] == 'up-sells' ) {
    remove_action('woocommerce_after_shop_loop_item','tinvwl_view_addto_htmlloop',10);
    }
    }add_action ('woocommerce_after_shop_loop_item','ssheds_remove_upsell_wishlist');

    This works fine for all the up-sell products all display without the wishlist button except for the first product which still has it showing, any ideas why this might be happening?

    1. Hi Ben, had a similar issue yesterday with a client. Instead, try to remove_action for all products, and then add_action to re-add them if it’s not the up-sells (basically the opposite of what you’re doing). Let me know

  30. Hi,
    Is that possible to add a hook of “Estimated Delivery Time: 5 Days” for a particular shipping class (like ‘excessweight’) in Cart/Checkout page. Can you please post the hook on this?
    Thanks

    1. Hello Fawazk, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  31. Great read and checked out the plugins etc but still can’t find (or figure out) what to do.

    On my page that shows my products (product image, title, price, cart link and email link) I want to add some custom text (between the title and price). I know how to hack the files to add custom text but this would apply it to all products. I just want to add some text for a handful of products.

    Can anyone help with this?

    1. Hi Nathaniel, if those products have a tag or category in common, there are examples in this article – let me know

  32. Hello Rodolfo,

    How can I use a social share locker shorcode like this [shortcode]…[/shortcode] for lock add cart button in specific product ID ?

    Thanks you for your help.

    1. Hey Stan, thanks for your comment! You can “print” a shortcode via PHP: https://developer.wordpress.org/reference/functions/do_shortcode/ – this means you can then also use conditional logic. Hope this helps

  33. Ho Rodolfo and thanks for all the work you do.

    I am using 2 of your code snippets – single page with a defined product tag and I am trying to call your:

    “add_action( ‘woocommerce_single_product_summary’, ‘bbloomer_custom_action_above_title’, 5 );” hook conditionally using this.

    I am obviously missing a piece of the puzzle – I must be calling it wrong. I’m not asking you to code it for me, rather just point me in the right direction with respects to how to conditionally call this new function/hook.

    Any help much appreciated

    thanks

    1. Hey Simon, thanks for your comment! The conditional check goes inside the “bbloomer_custom_action_above_title” function – did you place it there correctly?

  34. Hi!

    I had a question about something that you didn’t cover in this post. How can you echo text based on the price?

    Ex:
    if price =<$20 then echo "x"
    if price =<$40 then echo "y"
    if price =<$60 then echo "z"

  35. Great resource, thank you.

    I’m banging my head against the wall on something though and wondered if you’d be willing to help me.

    In a nutshell, I need to display a text note on a single product pages for downloadable products. This should be pretty straightforward using “if( $product->is_downloadable() )” and it works with simple products but I can’t get it to work on any of my downloadable products that are also variable (which is all of them!).

    I’ve tried every approach and alternative I can think of but am completely stumped. Maybe you can spot where I’ve gone wrong:

    //add text note to product description page for all downloadable products
    add_action( 'woocommerce_before_add_to_cart_button' , 'append_download_note' );
    function append_download_note() {
    	global $product;
    	if ( $product->is_downloadable() ) {	
            echo '<p>Please note: a link to your downloadable product will be available on the purchase confirmation page.</p>';
        }
    }

    I can get this to work if I use

    if ( is_product() ) 

    or

     if ( $product->is_type( 'variable' ) ) 

    .

    I’ve also tried using the product category

    if ( has_term( 'Knitting Patterns' ) ) 

    but that doesn’t work.

    And tried

    if ( $product->is_type( 'variable' ) &&  $product->is_downloadable() ) 

    but no joy there either.

    Really scratching my head here. Any advice appreciated!

    1. Hey there 🙂 I guess it’s not the product that is downloadable – it’s the single “variation” i.e. the one that is selected from the dropdown. This is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  36. Thanks a lot! Exactly what I needed.

    1. Bummer that you wouldn’t share the solution… I get it though, have the same situation with a project that’s run way over budget and need to hide some stuff based on it being variable and virtual. Because the project’s over budget I can’t get anyone to pay for what I wouldn’t think would be an extraordinary solution. If anyone else has any ideas, I would love to hear them!

  37. Hi, thanks for all this info. What I’m trying to do is get the price to change on the product page when specific variables are selected. Right now, it keeps just showing the range and only shows the actual price on the checkout page. Please assist in how I should go about this or where I should look for more info.

    1. Hey Ditshego, thanks for your comment! That to me sounds like a theme bug / plugin conflict. Take a look at this tutorial to see how to troubleshoot: https://businessbloomer.com/woocommerce-troubleshooting-mistakes-to-avoid/

  38. Hi, Rodolfo, thanks for your great post.
    I have a woocmmerce website, there has two difference category and sub category for product. and two custom header image for different category and its sub category, I used divi theme.

    Category group like WFCA, Franklin

    I want a function for single product page, if the product from WFCA then header image should be WFCA header image otherwise it should be Franklin header image,

    would you please help on this by a example functions

    thanks

    1. Faruk, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  39. Hi I have used some conditional logic throughout my site to alter the display of the Price. Particularly to show variation prices as ‘From: 0.000’ in some places and ‘4.00 – 5-00’ in others.

    One of the conditions I’m using is the related products one from this article:
    if ( is_product() && $woocommerce_loop[‘name’] == ‘related’ ) {

    My question is, is there a similar conditional that exists for upsells and crosssells? Because I can’t seem to target those prices.

    1. Hey Craig, thanks for your comment! Try with:

      
      $woocommerce_loop['name'] == 'up-sells'
      
      $woocommerce_loop['name'] == 'cross-sells'
      
      
    2. Thank you! Got that to work nicely in a conditional along with the related. Happy days!

  40. hi rodolfo –

    thank you for all the great work you’re doing to help!

    i have a scenario which i need some help with…

    for customers who need to purchase service “X” for a number of named people, i need to restrict them to making multiple individual purchases of service “X” – within the same transaction.

    so tom needs to purchase a total of 3 of service “X” for john, jane and megan. so i need to restrict him to place 3 individual orders within the same transaction.

    the way i need to do this is simply to remove the quantities option from the product page of service “X”.

    i tried adding the following css code, but it removes the quantities option from ALL services – and i only want it removed from the product page of service “X”

    .quantity.buttons_added {
    display: none;
    }

    i am not a programmer, and came across your site via a google search…and feel there’s something on this page here:

    https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/

    …but just don’t quite know what it is that could be used to help.

    i would dearly appreciate any guidance you can provide.

    many thanks.

  41. Hi dear Rodolfo,

    What if I want a scenario where if product(s) having tag “A” is added to the cart, then product(s) having tag “B” should not be able to be added to the cart together. And vise versa; if product(s) added to cart has tag “B” then it should prevent products having tag “A” from being added to the tag.

    I appreciate all your efforts, expecting to hear from you. Thanks again

    1. Hey Donald, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  42. Hi,

    Thank you for the article. I’ve bookmarked it for future reference. Unfortunately, I can’t seem to get the function to modify the cart based on contents to work. As a test, I have this:

    //if cart contains product id 84
    function bbloomer_find_id_in_cart() {
    global $woocommerce;     
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
               
        $product = $values['data'];
       
        if ( $product->id == 84 ) {
            echo "hooplah!";
        } else {
    		echo "garbanzo";
    	}
       
    }
    }
    

    I added to the end of functions.php. I added the “else” operator just to see if I could get any output. I don’t really need to echo text, but rather I’m going to run some javascript. I suppose I could just use javascript , but I would prefer a server-side option to keep the end user’s experience clean and snappy.

    I’m still in development, and I’m just using a child theme of twentyseventeen. I know there have been some major updates to WooCommerce which might have changed terminology. Could this be the case? Thank you for your guidance!

    1. Uhm, just wondering if you’re calling the function bbloomer_find_id_in_cart() via a hook? Otherwise it’s not going to echo anything

  43. Hi Rodolfo,

    Just wanted to say a quick thanks for all the content you put out around Woocommerce it definitely helps a lot.
    My question is I’m new to PHP and I’m trying to organise my affiliate site so when someone clicks on the external product image/add to cart button/title on the shop page, it opens up the affiliate link in a new tab.

    I’ve been using the below code for just the add to cart button.
    Do you know what I could do to make it applicable to the product image/title/add to cart all the same time?

     
    // Product Loop Add to cart target blank
    add_filter( 'woocommerce_loop_add_to_cart_link', 'add_target_blank', 10, 2 );
     
    function add_target_blank( $link, $product ){
     
    // I simply added target="_blank" in the line below
    $link = sprintf( '<a href="%s" target="_blank" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->product_type ),
            esc_html( $product->add_to_cart_text() )
        );
    return $link;
    

    Thanks Heaps

    1. Jesse, thank you for your comment! You will need to basically change the “loop” product image and product title link – I recommend you study the “hooks” on the loop pages so that you can find out how to remove the existing and replacing it with yours: https://businessbloomer.com/woocommerce-visual-hook-guide-archiveshopcat-page/

  44. Hi,

    How I can do to retreive the attribute of product ?

    there is any way with has_term ?

    thanks

  45. Hi,
    Could you give another example, but for the single product page sidebar? I’ve tried adding the code below to the “PHP Code Widget” in the sidebar, but it doesn’t work properly as it returns “test6” in the sidebar for every single product!

    Thanks!

    <?php
    if (is_product_tag( 'adexample1' )) {
    echo "test1";
    } elseif (is_product_tag( 'adexample2' )){
    echo "test2";    
    } elseif (is_product_tag( 'adexample3' )){
    echo "test3";  
    } elseif (is_product_tag( 'adexample4' )){
    echo "test4";  
    } elseif (is_product_tag( 'adexample5' )){
    echo "test5";  
    } else {
    echo "<p>test6</p>";
    }
    ?>
    
    1. Hey Ben, thanks for your comment! Pay attention at is_product_tag: that’s a conditional tag that only works on a tag page, and not on the single product page. Instead, you should use this: “PHP: do something if product belongs to a tag”, I think it’s the 5th or 6th example. Let me know!

  46. Dear sir, i want postocode based simple static delivery time for each postcode. if you have any ideal please help me.

    1. Hey Kedar, thanks for your comment! You’ll need a plugin for that, sorry 🙂

  47. Thanks for your great tutorial. I want to do a different thing but don’t know how to do it?

    There is a ‘verified buyer’ options in woocommerce plugin that is applicable only for them who buy something and leave their review they are only be considered as a verified buyer and there is a text shown after commenter/reviewer name as ‘verified buyer’.

    I want to show ‘verified buyer’ text even if customer doesen’t buy anything and there might be a option in backend to allow admin to enable verified buyer or disable it for any customer. If enable the option customer will be considered as verified buyer otherwise no. Is that possible? Can you help me please?

    Sorry for my poor English.

    1. Emran, thanks so much for your comment! Unfortunately I have no idea in this case, and I’d suggest you talk to the plugin developers to see if they can help (you’re paying them for this sort of help!). Let me know how it goes 🙂

  48. Hi Rodolfo,
    Your tutorials are great! I have one issue that has been difficult in resolving, and wondered whether you could help?
    It is concerning conditional logic of product attributes and variations. As a photographer I want users to be able to select a photo size, and then a display option (I have these all set up and working OK). Next, I want two other select boxes to show only when certain selections are made.

    ie. If the display option is ‘Print Only’ – nothing need happen. However, if the option is ‘Framed Print’, then I would like two more options (Mount Colour and Frame Style) to show beneath.

    Can this be done programmatically as I can’t find a way to do it without having to purchase the likes of Gravity forms?

    Regards
    Rob

    1. Hiya Rob, thanks for your comment! I was going to suggest Gravity Forms until I read your last sentence 🙂 Either way, this is way more efficient and cost effective than trying to do it and develop it in JQuery, which would take you time and money anyway in my opinion. Hope this helps!

  49. Hi
    I also had problems with the above displayed examples.
    It all depends on the theme. I made one myself and
    changed the loop in woocommerce.php
    With this code the archive-product.php can finally be reached and altered.
    Thanks for all your tutorials.
    regards
    theo

    1. Thanks for your feedback Theo!

  50. Hello, thank you so much for your helpful website. I’m learning PHP and struggling to add handling fees to my cart, but only for certain product categories (the ones that are actually physical and to be shipped, not the digital ones). The category slugs are ‘printed’ and ‘imprimee’, or their ID numbers are 57 and 77. I tried many things but can’t figure out how to correctly add the product category condition to the php code:

    
    add_action( ‘woocommerce_cart_calculate_fees’,’endo_handling_fee’ );
    function endo_handling_fee() {
     global $woocommerce;
    
    if ( is_admin() &amp;&amp; ! defined( ‘DOING_AJAX’ ))
    return;
    
    $fee = 3.00;
     $woocommerce-&gt;cart-&gt;add_fee( ‘Handling’, $fee, true, ‘standard’ );
    }
    
    
    1. Hey Johanna, thanks for your comment! You can see an example of conditional “add fee” here: https://businessbloomer.com/woocommerce-add-fee-to-cart/

      It’s not the same example you’re referring to but combining the info in this tutorial and the snippet I referenced should get you closer 🙂

      Let me know!

  51. Hi Rodolfo!

    I tried out the snippit for the single product page. I only want to show a message before the add to cart button on variation products.
    Question is, can I use a add action inside the snippit? Because it does not work.

    Here’s my code.

     // Laat de tekst voor de voorraadstatus alleen zien op variable producten
    add_action( 'woocommerce_after_single_product_summary', 'bbloomer_single_product_type' );
     
    function bbloomer_single_product_type() {
     
    if( $product->is_type( 'variable' ) ){
    	// Voegt een tekst toe voor de voorraadstatus
     add_action( 'woocommerce_before_add_to_cart_button', 'return_policy', 10 );
    function return_policy() {
        echo '<h2 class="quick-overview">Voorraadstatus: Kies eerst een uitvoering.</h2>';
    }
     
    } elseif( $product->is_type( 'external' ) ){
     // do something
    } elseif( $product->is_type( 'grouped' ) ){
     // do something
    } 
     
    }
    
    1. Hey Sander, thanks for your message! There is something wrong in your code, and it can simply be fixed by removing the first action, using your “inside-the-function” action instead, and use the conditional logic inside the function, without the need of calling a new add_action. Not sure if this is clear enough, but hope it helps a little 🙂

      1. Thanks for your reply Rodolfo. So i tried out some different things, from which all ended in disaster 😉

        I removed the first action and used the action i had inside the conditional logic. I also tried using only the function but that gave errors.

         
        // Laat de tekst voor de voorraadstatus alleen zien op variable producten
         add_action( 'woocommerce_before_add_to_cart_button', 'voorraad', 10 );
        function voorraad() {
          
        if( $product->is_type( 'variable' ) ){
        
            echo '<h2 class="quick-overview">Voorraadstatus: Kies eerst een uitvoering.</h2>';
          
        } elseif( $product->is_type( 'external' ) ){
         // do something
        } elseif( $product->is_type( 'grouped' ) ){
         // do something
        } 
          
        }
        
        1. This function should work. What error are you getting?

          1. I’m getting this error:

             
            Fatal error: Call to a member function is_type() on null in E:\xampp\htdocs\global\wp-content\themes\furnicom-child-theme\functions.php on line 177 
            1. Line 177:

              if( $product->is_type( ‘variable’ ) ){

              1. Hey Sander, thanks for that! I’d say you need to declare the global $product as the snippet doesn’t know what it’s inside. Add this inside the function and let me know:

                global $product;
                
                1. Thanks Rodolfo! That was it. Is that something that was missing in the original snippet, or is this only for my example?

                  1. Not sure 🙂 Let’s see if some other reader reports the same error!

  52. If I have a subscription, the reoccurring totals section for shipping is always listed as: Shipping Via “whatever method name” then “Price(or “Free” if price is 0.) I wanted to know how do I remove the stupid Shipping via hook, because it is extremely redundant because I offer a subscription with free shipping. So in the order details it literally says “Shipping via Free Shipping” “Free.”

    Thanks.

    1. Hey Adam, thanks for your comment! Your issue is a little off-topic… however I happen to have a resource that might be of help: https://businessbloomer.com/woocommerce-remove-shipping-labels-cart-checkout-page-e-g-flat-rate/. Let me know 🙂

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *