My Courses > CustomizeWoo > Module 5 > Lesson 02: Conditional Logic

Conditional Logic

MARK LESSON AS COMPLETE

Conditional logic allow you to display content or run PHP functions on a particular WP/WC page depending on what conditions that page matches.

Video

Please note: English captions are enabled by default (click on “CC” in the video player to disable). Also, you can click on the “gear” icon to manage quality and playback speed. Enjoy!

Sorry, this video is visible to logged in and fully registered students only.
If you already enrolled in this course, please LOG IN
Otherwise, please enroll in the FREE / PRO COURSE
For any other queries, feel free to get in touch

Useful Links

WordPress Conditional Tags: https://codex.wordpress.org/Conditional_Tags

WooCommerce Conditional Tags: https://docs.woocommerce.com/document/conditional-tags/

WooCommerce Conditional Logic – Tags, Examples & PHP: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/

19 thoughts on “Conditional Logic

  1. Hello, Rodolfo
    I am wondering is an if condition depend on screen width or device type?
    I know that I can using CSS/Javascript to show/hide some elements using media query. but the elements still loading on the DOM but hidden.
    So for the best performance it will be better to control it using the PHP if we can handle this.

    Thanks in advance

    1. Hey Hesham, not really, no. The only conditional available to you is https://developer.wordpress.org/reference/functions/wp_is_mobile/

  2. Hello Rodolfo,
    I try to translate some strings the customer receives by email. But I want these strings to be translated conditionally, based on the product category in order.
    So, I wrote this snippet, but nothing happens:

    add_action( 'woocommerce_thankyou', 'bbloomer_custom_woocommerce_auto_complete_order', 5 );
      
    function bbloomer_custom_woocommerce_auto_complete_order( $order_id ) { 
      
       // 1. Get order object
       $order = wc_get_order( $order_id );
      
       // 2. Initialize $cat_in_order variable
       $cat_in_order = false;
      
       // 3. Get order items and loop through them...
       // ... if product in category, edit $cat_in_order
       $items = $order->get_items(); 
          
       foreach ( $items as $item ) {      
          $product_id = $item->get_product_id();  
          if ( has_term( 'music', 'product_cat', $product_id ) ) {
             $cat_in_order = true;
             break;
          }
       }
      
       // 4. Add filter only if $cat_in_order == true   
       if ( $cat_in_order ) {
    add_filter( 'gettext', 'custom_translate_woocommerce_strings', 999, 3 );
    function custom_translate_woocommerce_strings( $translated, $untranslated, $domain ) {
     
       if ( ! is_admin() && 'woocommerce' === $domain ) {
     
          switch ( $translated ) {
     
             case 'Just to let you know — we\'ve received your order #%s, and it is now being processed:':
     
                $translated = 'This is my custom translation:';
                break;
             
          }
     
       }   
      
       return $translated;
     
    }   
       }
        
    }

    If I use only function custom_translate_woocommerce_strings alone it is working, but I want to use it conditionally. Your advice, please?

    1. Hey Marcel! So, your code is wrong. The controlling function is always “custom_translate_woocommerce_strings” so the conditional should be inside that function, not elsewhere. Besides, you don’t need the “woocommerce_thankyou” hook.

      Also, the “gettext” filter does not allow you to use many conditionals, I mean you can use is_home() or something like that but there is no way to detect whether this is an email and which category is in the order I’m afraid.

      WooCommerce “hardcoded” those strings without giving us additional filters or actions, which is bad from a customization point of view.

      In this case, you have no other option: duplicate the email template and place it in the /woocommerce/emails folder of your child theme, and write your conditional inside the template itself. Source: https://docs.woocommerce.com/document/template-structure/

  3. Hello, Rodolfo.

    I followed how to add content to a specific order email here: https://www.businessbloomer.com/woocommerce-add-extra-content-order-email/.

    Please guide me on how I can add specific content to the email if one of the products purchased belongs to a specific product category.

    1. Hi Marcel! You have access to the $order variable, therefore check https://www.businessbloomer.com/woocommerce-check-product-category-order/ and let me know

      1. I managed to add a custom note in the email depending on the product category. Please check this code, I tried and it works:

        /* Add info about a product from a specific category to the order email. */
        add_action( 'woocommerce_email_before_order_table', 'add_info_to_order_email', 5, 4 ); 
        function add_info_to_order_email( $order, $sent_to_admin, $plain_text, $email ) {
        	// Only customers need to know about the delivery times.
        	if ( $sent_to_admin ) {
        		return;
        	}
        	
        
           $order_has_this_term_product = false;
           $order_has_another_term_product = false;
        
        $items = $order->get_items();
        foreach ( $items as $item_id => $item ) {
          $product = $item->get_product();
          
         
          if ( has_term( 'this-term', 'product_cat', $product->get_id() ) ) {
              $order_has_this_term_product = true;
          }
          if ( has_term( 'another-term', 'product_cat', $product->get_id() ) ) {
              $order_has_another_term_product = true;
          }
        }
        
        
        if ( $order_has_this_term_product) {
          if ( $plain_text ) {
              echo "\nNOTE: Info about this term.\n";
          }
          else {
            echo '<p><strong>Note</strong>: Info about this term.</p>';
          }
        }
        if ( $order_has_another_term_product) {
          if ( $plain_text ) {
            echo "\nNOTE: Info about another term.\n";
          }
          else {
            echo '<p><strong>Note</strong>: Info about another term.</p>';
          }
        } 
        }
        

        The problem is that I don’t know where or how I should add:

        &&$email->id == 'customer_processing_order'

        so that these messages appear only in the processing order email.

        Thanks.

        Marcel

        1. I found this solution:

          if ( $email->id == 'customer_processing_order' && $sent_to_admin ) {
          		return;
          	}

          and it is working.
          Teacher Rodolfo, your thoughts, please?

          1. This would exit from the function and not execute it if the email is “processing order” (it would work for ALL other customer emails). If that’s what you wanted, then it’s perfect

  4. Hello, Rodolfo!

    Case:
    I need to get the following result: I want to display a notification in the cart about the amount remaining to reach the free shipping threshold, which should be visible ONLY IF product “X” has been added to the cart.
    If product “X” has not been added to the cart, I do not want a notification.

    The scenario is based on your snippet presented here: https://www.businessbloomer.com/woocommerce-add-need-spend-x-get-free-shipping-cart-page/, but I can’t set the right condition. Can you please guide me?

    Here is the snippet I tried to write:

    /**
     * @snippet Check if Product ID is in the Cart and show a notification in cart - WooCommerce
     */
       
    add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart_1' );
        
    function bbloomer_find_product_in_cart_1() {
      
       $product_id = 20;
      
       $product_cart_id = WC()->cart->generate_cart_id( $product_id );
       $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
      
       if ( $in_cart ) {
     
        add_action( 'woocommerce_before_cart', 'bbloomer_free_shipping_cart_notice' );
      
    function bbloomer_free_shipping_cart_notice() {
      
       $min_amount = 50; //change this to your free shipping threshold
       
       $current = WC()->cart->subtotal;
      
       if ( $current < $min_amount ) {
          $added_text = 'Get free shipping if you order ' . wc_price( $min_amount - $current ) . ' more!';
          $return_to = wc_get_page_permalink( 'shop' );
          $notice = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), 'Continue Shopping', $added_text );
          wc_print_notice( $notice, 'notice' );
       }
      
    }
    } 
       }
    1. Hi MArcel, you can’t nest functions like that – you need to rewrite the code and place it inside a single function.

      Should be like this:

      
      add_action( 'woocommerce_before_cart', 'bbloomer_free_shipping_cart_notice' );
         
      function bbloomer_free_shipping_cart_notice() {
      
         // check products in the cart
         $product_id = 20;
         $product_cart_id = WC()->cart->generate_cart_id( $product_id );
         $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
      
         // exit if no product
         if ( ! $in_cart ) return;
      
         // start with banner code   
         $min_amount = 50;
         $current = WC()->cart->subtotal;
         // etc.
      
      }
      
      
      1. I suggest using this for checking amount in case you change it in future. Also consider this only working if your free shipping is set to world wide.

        $free_shipping_settings = get_option ('woocommerce_free_shipping_settings' );
        $min_amount = $free_shipping_settings['min_amount'];
        
  5. Hello Rodolfo!

    I would like t know if a conditional logic applies to a product category, then all subcategories that belong to that parent category will get the same treatment?

    1. Good question Marcel! No, conditional logic usually targets a category ID or category slug or category name, hence it doesn’t know and doesn’t care whether a category is a parent or a child one. You’ll need to specify a parent category and all its subcategories in case you want to apply a conditional rule to a “group” of categories… otherwise you could study https://codex.wordpress.org/Function_Reference/cat_is_ancestor_of, which should help you target “all subcategories” of a category ID. Hope this helps!

      1. Ok. It seems to be with an advanced grade of difficulty… What about assigning a “tag” to the (sub) categories in discussion and make the function based on that “tag”?

        1. Hey Marcel πŸ™‚ If you require to target a set of subcategories, no, you can’t add a “tag” to them. Unless you assign them to an additional product category e.g.:

          subcat1
          subcat2
          subcat3 (cat 1)
          subcat4 (cat 1)

          Let me know πŸ™‚

      2. I found out if both “parent” and “child” categories are ticked on the product page, the conditional logic rule applies even the PHP code includes just the “parent” category. But if just “child” category is ticked, the conditional rule does not apply anymore for the “parent” category.
        https://www.screencast.com/t/80I1oImc

        1. Excellent!

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

If you are writing code, please wrap it between: [php]code_here[/php]

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