Reliably check for the checkout page earlier than is_checkout()

The is_checkout() method is the standard to build conditionally logic around on whether the user is on the checkout page or not.

But what if it is too early for is_checkout() to be available?

Paying attention to the WordPress load lifecycle, is_checkout is available “too late” in the cycle.

It may work when called in a function hooked to template_reditect or wp_head.

If you need it before the template has loaded, is_checkout renders completely useless.

So, you need to get creative to check whether the current page is the checkout page or not.

A solution I came up with recently for a project is like so:

add_action('wp_loaded', function(){
  
    //Get the page ID from the WooCommerce option.
    $checkout_page_id = get_option( 'woocommerce_checkout_page_id' );

    // Transform the obtained string value into an integer.
    $checkout_page_id = (int)$checkout_page_id;

    // Get the Request Slug.
	  $request_uri = $_SERVER['REQUEST_URI'];
	  // Get the Post ID from the obtained slug.
	  $post_id = url_to_postid($request_uri);

    // Compare the two IDs.
	  if( $post_id == $checkout_page_id ) {
		    exit('this is the checkout page'); // If the IDs match identically, then we are on the checkout page.
	  }
});

The example above uses a combination of retrieving the checkout page ID stored in the wp_options table as a WooCommerce option.

Then obtains the Page ID of the current query.

When the IDs match, we are on the checkout page.

How to add text or an icon to the Shipping Method label in WooCommerce

For your available shipping methods, you may want to add an image, text, or any other type of indicator at the farther right corner of the Shipping Method name.

You can do so with the woocommerce_cart_shipping_method_full_label filter.

This filters the shipping method full label and accepts two parameters, $label, the label of the shipping method, and $method, the actual method object.

To filter a specific method label, you can reference the method by its id.

You can access the method_id property of the method object.

Then set different cases in a switch statement covering the different methods you want to filter.

At the end, always return $label.

/*
* Filter the shipping method labels and add an extra text string to the right side of the method's label.
*
* @param $label. The shipping method label.
* @param $method. The method object.
* @return $label. The shipping method label, whether modified or left intact.
*/
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 ); 

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) { 
   // Use the condition here with $method to apply an image or text string to a specific method.      
	
	switch($method->method_id){
		case 'free_shipping':
			$label = $label . '<span>FREE</span>';
			break;
		case 'flat_rate':
			$label = $label . '<span>Icon</span>';
			break;
	}
	
	
   return $label; // Always return $label.
}

This is tested and works perfectly with CheckoutWC 9.0.25 (the latest version at the time of writing).

Prevent the CheckoutWC’s Side Cart from opening when editing a page with Elementor.

There is a problem with Elementor and CheckoutWC, and that is, when you try to edit any page in the Elementor editor, and you save a change, the CheckoutWC’s Side Cart will auto-open for some strange reason.

This problem is somewhat complex to solve as essentially, the Elementor editor lives in its own environment. This means that if you try to run a WordPress hook from the WordPress core or a third-party plugin, it may or may not work.

I found a workaround to get rid of the Side Cart auto opening when editing a page with Elementor.

It is not the most elegant solution, but hey, it works!

The logic behind it is simple: Detect if the Elementor editor exists on the current page, with JavaScript and CSS selectors. If it does, hide the Side Cart’s floating icon, drawer element, and the background overlay.

See the code below:

function custom_inline_script_for_elementor() {
    // Check if we are in the admin area and return early if we are not
    if (is_admin()) {
        return;
    }

    ?>
    <script>
    (function() {
        var checkAndHide = function() {
            if (document.body.classList.contains('elementor-editor-active')) {
                var elementsToHideIds = ['cfw-side-cart-floating-button', 'cfw-side-cart-overlay', 'cfw-side-cart'];
                elementsToHideIds.forEach(function(id) {
                    var elementToHide = document.getElementById(id);
                    if (elementToHide) {
                        elementToHide.style.display = 'none';
                    }
                });
            }
        };

        // Check immediately
        checkAndHide();

        // Then check repeatedly for a few seconds
        var intervalId = setInterval(checkAndHide, 500);

        // Stop checking after 5 seconds
        setTimeout(function() {
            clearInterval(intervalId);
        }, 5000);
    })();
    </script>
    <?php
}
add_action('wp_footer', 'custom_inline_script_for_elementor');

Disable the Side Cart conditionally in CheckoutWC on specific pages.

The Side Cart is convenient in any store to help users access the products they are about to purchase.

But at the same time, it may also be convenient not to have it on all pages on your website.

Some pages require more attention from the user.

So a simple way you have to prevent CheckoutWC’s Side Cart from appearing in specific pages is using the cfw_disable_side_cart filter.

In short, the cfw_disable_side_cart filter intercepts the on/off option that dictates if the Side Cart is enabled or disabled.

Following the filter’s name, you need to set it to true, and the Side Cart won’t pop up.

To dynamically change the value while detecting the page, you can use a preg_match function to check if certain slug is part of the URL.

Then wrap the preg_match evaluation in a boolval() function so it returns explicitly a boolean.

For example, if you want to disable the Side Cart on your About Us page, and the slug is yourwebsite.com/about-us/, you can do so as follows:

add_filter(
	'cfw_disable_side_cart',
	function() {
		return boolval( preg_match( "/^\/about-us/", $_SERVER['REQUEST_URI'] ) );
	}
);

Display the discounted amount per product on the Order Details in WooCommerce.

After a customer completes a purchase in your WooCommerce store, they get redirected to the Order Received page.

This Order Received page contains information about the purchase, like the Order Number, the customer’s full name, email address, and payment method used, and there is also a table featuring the list of purchased items called Order Details.

Each item in the Order Details table usually has the Product name, Amount, Price, and, at the very end, a calculation of the order Subtotal, Shipping, Taxes (if any), and if you offered a discount, the discount for the total purchase.

Let’s say you are running a special deal to get sales rolling. You want to show your customers how much they are saving per item after the purchase.

Nice idea.

The problem is that WooCommerce does not have an option to display the discount per product.

So, how can you add one?

You can leverage the woocommerce_order_item_meta_end action.

In short, this action hook allows you to add custom content at the end of each order item.

The woocommerce_order_item_meta_end action allows you to use three parameters: item ID, item, and order.

First, you want to get the original item price, dividing the item subtotal by the item quantity the customer purchased.

Now, get the actual price paid per item, dividing the item total by the item quantity.

In WooCommerce, you may create Coupons that only apply to specific products. You may want to run the code only for products that qualify for the discount. Non-discounted products would not need to display a discounted price.

So, if the price the customer paid per a specific item is less than the original price of the same item, then show the discounted amount for that product.

An item will be excluded from the function when it fails this condition.

The resulting code looks like this:

add_action('woocommerce_order_item_meta_end', 'display_product_discount', 10, 3);
function display_product_discount($item_id, $item, $order) {
    // Get the original product price from the order item data
    $original_price = (float) $item->get_subtotal() / $item->get_quantity();

    // Get the actual price the customer paid for the product in the order
    $order_price_per_item = (float) $item->get_total() / $item->get_quantity();

    // Check if the product was discounted
    if ($order_price_per_item < $original_price) {
        // Calculate the discount per product
        $discount_per_product = $original_price - $order_price_per_item;

        // Display discount per product and discounted price with inline CSS
        echo '<div class="product-discount">';
        echo 'Discount: ' . wc_price($discount_per_product) . '<br>';
        echo '<span style="color: green; font-weight: bold;">Price after discount: ' . wc_price($order_price_per_item) . '</span>';
        echo '</div>';
    }
}

This is the final result

Add a custom button to CheckoutWC’s side cart

CheckoutWC side cart by default allows you to display a ‘Proceed to Checkout’ button and a Continue Shopping button. Sweet.

But what if you want to add a custom button that does something different, or more interesting that just redirecting the user to the checkout page or back to the shop?

You can add a custom button with the cfw_after_side_cart_proceed_to_checkout_button action in CheckoutWC.

Simply, create a function that outputs the button HTML structure, then hook it into the action above mentioned.

Something as follows:

add_action('cfw_after_side_cart_proceed_to_checkout_button', 'obi_custom_side_cart_button');

function obi_custom_side_cart_button(){
	
	echo '<a id="custom_side_cart_button" href="#" style="background:#FF7500" class="cfw-primary-btn cfw-side-cart-checkout-btn"> My Side Cart Custom Button </a>';
	
}

The end result:

How to add a custom icon to each shipping method in WooCommerce

Shipping methods define how the purchase will be delivered to your customer.

Commonly, the shipping service is taken care of by a company. Some of the shipping companies are larger than others.

You can identify the Shipping Method with a label in the shipping method settings in WooCommerce.

But if you feel the shipping label is not enough, you can add an icon to it.

It can be the company’s logo or any other indication that the user can better familiarize themself with.

WooCommerce provides a filter woocommerce_cart_shipping_method_full_label that allows you to retrieve the label of a specific shipping method, make changes, then return the result you have created.

A basic implementation of the filter would be to detect if the shipping method is ‘Free Shipping’ and add a specific custom icon:

add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 ); 

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) { 
   // Use the condition here with $method to apply the image to a specific method.      
	
	if($method->method_id == 'free_shipping'){
                $label = $label . '<img src='methodIcon.png'/>
        }
	
	
   return $label; 
}

Now, if you want to detect multiple shipping methods, instead of an if conditional, you can use a switch statement, better suited for multiple cases. The function then will return $label as many times as cases are processed from the switch statement.

Change the Billing fields position in CheckoutWC

In the WooCommerce standard checkout form, you are first asked for personal details like First Name, Last Name, Email Address, etc. Then, immediately you are asked to fill up the Billing Address. That’s nice in some cases, but it can be improved.

CheckoutWC, by design, changes this behavior by switching priorities between the Billing Address and Shipping Address, being the Shipping Address the first option right after the customer’s personal details.

The not-so-good thing is that, by default, it sends the Billing Address option right to the last step.

And there aren’t any options in the CheckoutWC settings to customize the field position.

However, it can still be changed with a bit of code.

So first things first, you need to identify where the Billing Address fields are on the checkout page.

Then, decide on a place to move it.

For this example, let’s move the Billing Address fields to the first step in the checkout page, which is the Information tab.

The destination place will be right below the Shipping Address.

Let’s lay out the steps you need to make the change.

First, “unhook” the Billing Address fields from the Payment tab.

remove_action( 'cfw_checkout_payment_method_tab', 'cfw_payment_tab_content_billing_address', 20 ); 

Second, hook it after the Shipping Address.

add_action( 'cfw_checkout_after_shipping_address', 'cfw_payment_tab_content_billing_address' );

That’s all! It’s that simple.