fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← WordPress

WordPress / 14 MIN READ

🎨 Tutorial: Customizing a WooCommerce Checkout Page with PHP Templates 🚀

🎨 Tutorial: Customizing a WooCommerce Checkout Page with PHP Templates 🚀 The WooCommerce Checkout Page is a critical step in your store's sales funnel. C

From the original Fervor library. Examples may use older package versions.

🎨 Tutorial: Customizing a WooCommerce Checkout Page with PHP Templates 🚀

The WooCommerce Checkout Page is a critical step in your store’s sales funnel. Customizing it with PHP gives you full control over its layout and functionality. In this tutorial, we’ll walk through overriding and editing the checkout template to tailor it to your store’s needs.


🔧 What You’ll Learn:

  1. How to locate and override the WooCommerce checkout template.
  2. How to customize the template layout and fields using PHP.
  3. Tips for adding custom functionality and styling.

Step 1: Locate the Default WooCommerce Checkout Template

WooCommerce templates are stored in the plugin directory. The primary checkout template is found here:

/wp-content/plugins/woocommerce/templates/checkout/form-checkout.php

This file handles the overall structure of the checkout page.


Step 2: Copy the Template to Your Theme

To safely customize the WooCommerce checkout page:

  1. Navigate to your theme directory:

    /wp-content/themes/your-theme/
    
  2. Create a woocommerce folder if it doesn’t already exist:

    /your-theme/woocommerce/
    
  3. Inside the woocommerce folder, create a checkout folder:

    /your-theme/woocommerce/checkout/
    
  4. Copy the form-checkout.php file from WooCommerce into your theme’s checkout folder:

    /your-theme/woocommerce/checkout/form-checkout.php
    

WooCommerce will now use your custom form-checkout.php file instead of the default one.


Step 3: Customize the Checkout Template

Open your copied form-checkout.php file in a code editor. Here’s what you can do:


1. Rearrange the Layout

The default template uses the woocommerce_checkout action to insert content like billing fields, shipping fields, and the order summary.

Default Structure:

<?php
do_action( 'woocommerce_before_checkout_form', $checkout );

if ( ! $checkout->is_registration_enabled() && $checkout->is_registration_required() && ! is_user_logged_in() ) {
    echo esc_html( apply_filters( 'woocommerce_checkout_must_be_logged_in_message', __( 'You must be logged in to checkout.', 'woocommerce' ) ) );
    return;
}
?>
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( wc_get_checkout_url() ); ?>" enctype="multipart/form-data">
    <?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
    <div id="customer_details">
        <?php do_action( 'woocommerce_checkout_billing' ); ?>
        <?php do_action( 'woocommerce_checkout_shipping' ); ?>
    </div>
    <?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
    <h3 id="order_review_heading"><?php esc_html_e( 'Your order', 'woocommerce' ); ?></h3>
    <?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
    <div id="order_review" class="woocommerce-checkout-review-order">
        <?php do_action( 'woocommerce_checkout_order_review' ); ?>
    </div>
    <?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
</form>
<?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?>

Example: Move the Order Summary Above Customer Details

Replace this:

<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>

With this:

<h3 id="order_review_heading"><?php esc_html_e( 'Your order', 'woocommerce' ); ?></h3>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
    <?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>

2. Add Custom Content

You can insert custom banners, notices, or trust badges.

Example: Add a Trust Badge Below the Form Header

Insert this below do_action( 'woocommerce_before_checkout_form', $checkout );:

<div class="checkout-trust-badge" style="text-align: center; margin-bottom: 20px;">
    <img src="https://example.com/secure-checkout.png" alt="Secure Checkout" style="max-width: 200px;" />
    <p style="font-size: 14px; color: #555;">Your information is safe with us.</p>
</div>

3. Customize Billing and Shipping Fields

To customize fields, override the hooks woocommerce_checkout_billing and woocommerce_checkout_shipping.

Example: Add a Custom Field (e.g., Delivery Date)

Add this to your theme’s functions.php:

add_filter( 'woocommerce_checkout_fields', 'add_delivery_date_field' );
function add_delivery_date_field( $fields ) {
    $fields['billing']['delivery_date'] = array(
        'type'        => 'date',
        'label'       => __( 'Preferred Delivery Date', 'woocommerce' ),
        'required'    => false,
        'class'       => array( 'form-row-wide' ),
        'priority'    => 25,
    );
    return $fields;
}

To display this field in the checkout template, insert this where you’d like it to appear:

<?php woocommerce_form_field( 'delivery_date', $checkout->get_checkout_fields( 'billing' )['delivery_date'], $checkout->get_value( 'delivery_date' ) ); ?>

4. Validate Custom Fields

Ensure the custom field is validated before submission. Add this to your functions.php:

add_action( 'woocommerce_checkout_process', 'validate_delivery_date' );
function validate_delivery_date() {
    if ( ! empty( $_POST['delivery_date'] ) && strtotime( $_POST['delivery_date'] ) < strtotime( 'now' ) ) {
        wc_add_notice( __( 'The delivery date cannot be in the past.', 'woocommerce' ), 'error' );
    }
}

5. Add JavaScript for Interactivity

Enhance the checkout with custom JavaScript.

Example: Highlight Fields with Errors

<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.woocommerce-invalid').forEach(function(field) {
        field.style.border = '2px solid red';
    });
});
</script>

Step 4: Style Your Checkout Page

Use CSS to make your checkout visually appealing. Add custom styles to your theme’s style.css or enqueue a separate stylesheet:

function enqueue_checkout_styles() {
    if ( is_checkout() ) {
        wp_enqueue_style( 'custom-checkout-styles', get_stylesheet_directory_uri() . '/checkout.css' );
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_checkout_styles' );

Step 5: Test Your Checkout Page

  1. Add products to your cart and proceed to the checkout page.
  2. Verify that your changes appear correctly.
  3. Test the page on mobile devices and various browsers to ensure responsiveness.

🚀 Bonus Ideas for Checkout Customization

  1. Enable a Multi-Step Checkout: Break the process into steps (e.g., billing, shipping, payment).

    • Use plugins like WooCommerce Multi-Step Checkout or custom hooks.
  2. Add Payment Logos: Show accepted payment methods near the “Place Order” button.

    echo '<div class="payment-logos">
        <img src="https://example.com/paypal-logo.png" alt="PayPal" />
        <img src="https://example.com/visa-logo.png" alt="Visa" />
    </div>';
    
  3. Disable Unnecessary Fields: Remove unnecessary fields like company name or second address line.

    add_filter( 'woocommerce_checkout_fields', function( $fields ) {
        unset( $fields['billing']['billing_company'] );
        unset( $fields['billing']['billing_address_2'] );
        return $fields;
    });
    
  4. Add Exit-Intent Popups: Use tools like OptinMonster to capture users leaving the checkout.


🎉 Wrapping Up

By customizing the WooCommerce checkout template with PHP, you can create a streamlined and user-friendly experience tailored to your store. From rearranging layouts to adding custom fields and interactive elements, the possibilities are endless. 💳✨

Bonus CheckOut Code and Ideas

🎁 Bonus WooCommerce Checkout Code & Ideas for Customization 🚀

Your checkout page is where the magic happens (or doesn’t). To optimize it further, here are more bonus code snippets and ideas to improve the design, functionality, and user experience of your WooCommerce checkout page.


1. Auto-Apply a Coupon Based on Cart Conditions

Automatically apply a discount code when certain items or conditions are met.

Code Snippet:

add_action( 'woocommerce_cart_calculate_fees', 'apply_discount_based_on_cart' );
function apply_discount_based_on_cart() {
    if ( ! is_admin() && WC()->cart->subtotal > 50 ) { // Condition: Subtotal over $50
        WC()->cart->add_fee( 'Special Discount', -10 ); // $10 discount
    }
}

2. Add a Custom Thank-You Note on Checkout

Display a personalized message based on the total purchase amount.

Code Snippet:

add_action( 'woocommerce_checkout_order_review', 'add_custom_checkout_thank_you_message' );
function add_custom_checkout_thank_you_message() {
    $cart_total = WC()->cart->total;
    if ( $cart_total > 100 ) {
        echo '<div class="checkout-thank-you-message" style="margin: 15px 0; padding: 10px; background: #e6ffe6; text-align: center;">
            <p>🎉 Thank you for your generous order! You qualify for VIP support. ❤️</p>
        </div>';
    }
}

3. Make Checkout Fields Conditional

Show or hide specific fields based on user input (e.g., shipping methods).

Code Snippet:

add_filter( 'woocommerce_checkout_fields', 'make_fields_conditional' );
function make_fields_conditional( $fields ) {
    if ( isset( WC()->cart->needs_shipping() ) && WC()->cart->needs_shipping() ) {
        $fields['shipping']['shipping_instructions'] = array(
            'type'        => 'textarea',
            'label'       => 'Delivery Instructions',
            'required'    => false,
            'class'       => array( 'form-row-wide' ),
            'priority'    => 50,
        );
    }
    return $fields;
}

4. Add Social Login to Checkout

Let customers log in with Facebook, Google, or other social accounts for faster checkout.

Idea:

  • Use a plugin like Nextend Social Login or Super Socializer to integrate social login.
  • Position the login buttons at the top of the checkout form:
add_action( 'woocommerce_before_checkout_form', 'add_social_login_buttons' );
function add_social_login_buttons() {
    echo '<div class="social-login-buttons" style="text-align: center; margin-bottom: 20px;">
        <button style="background: #4267B2; color: white; padding: 10px; border: none;">Login with Facebook</button>
        <button style="background: #DB4437; color: white; padding: 10px; border: none;">Login with Google</button>
    </div>';
}

5. Highlight Errors Dynamically

When a user submits the form with errors, highlight the problematic fields with a red border.

Code Snippet:

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('.woocommerce-checkout');
    form.addEventListener('submit', function() {
        document.querySelectorAll('.woocommerce-invalid').forEach(function(field) {
            field.style.border = '2px solid red';
        });
    });
});
</script>

6. Add a Countdown Timer for Cart Expiration

Encourage urgency by adding a timer that shows how long the cart will be reserved.

Code Snippet:

add_action( 'woocommerce_checkout_order_review', 'add_cart_timer' );
function add_cart_timer() {
    echo '<div id="cart-timer" style="margin: 10px 0; text-align: center;">
        <p>🕒 Your cart is reserved for <span id="timer">10:00</span> minutes.</p>
    </div>';
    ?>
    <script>
        let time = 600; // 10 minutes in seconds
        const timerElement = document.getElementById('timer');
        const interval = setInterval(function() {
            const minutes = Math.floor(time / 60);
            const seconds = time % 60;
            timerElement.textContent = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
            time--;
            if (time < 0) {
                clearInterval(interval);
                timerElement.textContent = 'expired';
            }
        }, 1000);
    </script>
    <?php
}

7. Add a Custom Payment Method Icon

Customize payment methods by adding your own icons.

Code Snippet:

add_filter( 'woocommerce_gateway_icon', 'add_custom_payment_icons', 10, 2 );
function add_custom_payment_icons( $icon, $gateway_id ) {
    if ( 'paypal' === $gateway_id ) {
        $icon = '<img src="https://example.com/paypal-icon.png" alt="PayPal" />';
    }
    if ( 'stripe' === $gateway_id ) {
        $icon = '<img src="https://example.com/stripe-icon.png" alt="Stripe" />';
    }
    return $icon;
}

8. Offer Express Checkout for Returning Customers

Pre-fill returning customer details and show an “Express Checkout” button.

Code Snippet:

add_action( 'woocommerce_before_checkout_form', 'add_express_checkout_button' );
function add_express_checkout_button() {
    if ( is_user_logged_in() ) {
        echo '<div class="express-checkout" style="margin: 20px 0; text-align: center;">
            <a href="' . wc_get_checkout_url() . '" class="button">Express Checkout 🚀</a>
        </div>';
    }
}

9. Add an Order Bump (Upsell)

Suggest a low-cost item during checkout to increase the average order value.

Code Snippet:

add_action( 'woocommerce_checkout_after_order_review', 'add_checkout_order_bump' );
function add_checkout_order_bump() {
    echo '<div class="order-bump" style="background: #f9f9f9; padding: 15px; margin-top: 20px; text-align: center;">
        <p>✨ Add this exclusive product to your order for just $5!</p>
        <a href="' . wc_get_cart_url() . '?add-to-cart=123" class="button">Add to Cart</a>
    </div>';
}

10. Add a Gift Wrapping Option

Let customers select gift wrapping at checkout.

Code Snippet:

add_filter( 'woocommerce_checkout_fields', 'add_gift_wrapping_option' );
function add_gift_wrapping_option( $fields ) {
    $fields['order']['gift_wrapping'] = array(
        'type'        => 'checkbox',
        'label'       => 'Add Gift Wrapping for $5',
        'required'    => false,
        'class'       => array( 'form-row-wide' ),
    );
    return $fields;
}

add_action( 'woocommerce_cart_calculate_fees', 'apply_gift_wrapping_fee' );
function apply_gift_wrapping_fee() {
    if ( isset( $_POST['gift_wrapping'] ) && '1' === $_POST['gift_wrapping'] ) {
        WC()->cart->add_fee( 'Gift Wrapping', 5 );
    }
}

11. Add Testimonials to Checkout

Reassure customers with positive reviews or testimonials.

Code Snippet:

add_action( 'woocommerce_checkout_before_customer_details', 'add_checkout_testimonials' );
function add_checkout_testimonials() {
    echo '<div class="checkout-testimonials" style="background: #f4f4f4; padding: 10px; margin-bottom: 20px;">
        <p>⭐️⭐️⭐️⭐️⭐️ "The checkout process was super smooth!" - Happy Customer</p>
        <p>⭐️⭐️⭐️⭐️⭐️ "Love the secure payment options!" - Another Happy Customer</p>
    </div>';
}

12. Enable Guest Checkout with Email Verification

Allow guest checkout but verify the email to avoid errors.

Idea:

  • Use a plugin like WooCommerce Email Verification or write custom hooks to send an email and validate a token.

13. Show Delivery Estimates Based on Location

Use the shipping address to calculate an estimated delivery date.

Code Snippet:

add_action( 'woocommerce_review_order_before_payment', 'add_delivery_estimate' );
function add_delivery_estimate() {
    $days = 5; // Estimated delivery in 5 days
    $estimated_date = date( 'F j, Y', strtotime( "+$days days" ) );
    echo '<p>📦 Estimated Delivery: <strong>' . $estimated_date . '</strong></p>';
}

🚀 Wrapping It Up

These bonus ideas and code snippets will help you create a checkout page that stands out, enhances user experience, and drives conversions. Whether it’s trust badges, upsells, gift options, or dynamic features, the possibilities are

endless with WooCommerce! With a bit of creativity and PHP magic, you can tailor the checkout process to perfectly align with your brand and customer expectations.💳✨

Bonus Pro Tips

🎯 Bonus Pro Tips for Customizing WooCommerce Checkout Pages 🚀

The checkout page is the last stop before customers hit “Buy.” Optimizing it can dramatically boost conversions and create a memorable shopping experience. Here are bonus pro tips to elevate your WooCommerce checkout page beyond the ordinary:


1. Reduce Checkout Steps (One-Page Checkout)

  • Why It Matters: Fewer steps = faster purchases = happier customers.
  • Pro Tip: Use WooCommerce’s One-Page Checkout plugin or combine all fields (billing, shipping, and payment) on a single page.
  • Bonus: Pre-fill logged-in users’ details to further streamline the process.

2. Provide Multiple Payment Options

  • Why It Matters: More choices mean more sales.
  • Pro Tip:
    • Offer popular payment gateways like Stripe, PayPal, Apple Pay, Google Pay, and local methods like Klarna or Afterpay.
    • Display logos of accepted payment methods prominently on the checkout page to build trust.

3. Add Social Proof

  • Why It Matters: Shoppers trust other shoppers.
  • Pro Tip: Add testimonials, reviews, or real-time purchase notifications (e.g., “Sarah just bought this!”).
  • Tools like Fomo or TrustPulse can automate this.

4. Include Exit-Intent Offers

  • Why It Matters: Recover users who are about to leave without completing their purchase.
  • Pro Tip:
    • Use tools like OptinMonster to trigger popups with a discount or free shipping when users show exit intent.
    • Example: “Wait! Complete your order now for 10% off!”

5. Add Guest Checkout (No Account Required)

  • Why It Matters: Not everyone wants to create an account.
  • Pro Tip:
    • Enable guest checkout in WooCommerce settings to eliminate friction.
    • Add a checkbox for users to optionally create an account post-purchase.

6. Optimize for Mobile

  • Why It Matters: Over 70% of users shop on mobile devices.
  • Pro Tip:
    • Ensure the form is responsive and easy to fill on small screens.
    • Test using touch-friendly inputs and buttons.
    • Use auto-focus and input masks (e.g., auto-format credit card numbers) for better UX.

7. Remove Unnecessary Fields

  • Why It Matters: Too many fields lead to cart abandonment.
  • Pro Tip:
    • Remove optional fields like “Company Name” or “Address Line 2” if they aren’t necessary for your business.
    • Use plugins like Checkout Field Editor or custom code to trim down the form.

8. Show Order Details in Real-Time

  • Why It Matters: Transparency builds trust.
  • Pro Tip:
    • Dynamically update totals (including shipping and tax) as customers fill out details.
    • Use the woocommerce_checkout_update_order_review hook to refresh totals instantly.

9. Enable Auto-Detection for Addresses

  • Why It Matters: Faster checkout = higher conversions.
  • Pro Tip:
    • Integrate Google Places API for address auto-completion.
    • Plugins like Address Autocomplete for WooCommerce can simplify implementation.

10. Offer Cart Editing at Checkout

  • Why It Matters: Reduces frustration if customers need to make changes.
  • Pro Tip: Add a small “Edit Cart” link near the order summary so users don’t have to backtrack.

11. Add a Checkout Timer

  • Why It Matters: Creates urgency and reduces abandonment.
  • Pro Tip: Display a countdown (e.g., “Your cart will expire in 10 minutes”) to motivate quicker decisions.

12. Use Trust Signals

  • Why It Matters: Builds customer confidence.
  • Pro Tip:
    • Add SSL certificates for a secure checkout (and show the padlock icon in the browser).
    • Use badges like “100% Secure Payments,” “30-Day Money-Back Guarantee,” or “Trusted by 10,000+ Customers.”
    • Place trust signals near the “Place Order” button.

13. Reward for Completing the Purchase

  • Why It Matters: Creates a sense of value.
  • Pro Tip:
    • Offer a small discount or freebie on the next order for completing the purchase.
    • Example: “Get 10% off your next order as a thank-you!”

14. Use Behavioral Analytics

  • Why It Matters: Insights help you fix bottlenecks.
  • Pro Tip:
    • Use tools like Hotjar or Crazy Egg to monitor user behavior.
    • Identify where users drop off in the checkout process and make improvements.

15. Enable Multi-Language and Multi-Currency Support

  • Why It Matters: Expand your reach globally.
  • Pro Tip:
    • Use plugins like WPML for multi-language checkout.
    • Add currency switchers (e.g., WooCommerce Multi-Currency) to display prices in local currencies.

16. Follow-Up with Abandoned Cart Emails

  • Why It Matters: Recover lost sales.
  • Pro Tip:
    • Use plugins like CartFlows or Retainful to send automated abandoned cart emails.
    • Include a discount code or a friendly nudge: “Your items are waiting for you!”

17. Optimize Page Load Speed

  • Why It Matters: Slow pages kill conversions.
  • Pro Tip:
    • Compress images and use lightweight themes.
    • Enable caching and use a CDN for faster delivery.

18. Display Delivery Estimates

  • Why It Matters: Helps users plan purchases.
  • Pro Tip: Show estimated delivery dates based on location and shipping method.

19. Provide Live Chat or Support

  • Why It Matters: Reduces confusion or hesitation during checkout.
  • Pro Tip:
    • Add live chat using tools like Tawk.to or Zendesk Chat.
    • Include an FAQ section near the checkout to answer common questions.

20. A/B Test Regularly

  • Why It Matters: Optimized experiences improve conversions.
  • Pro Tip: Test elements like:
    • CTA button text (“Place Order” vs. “Complete Purchase”).
    • Field layouts (single vs. multi-column).
    • Positioning of trust badges or upsells.

🚀 Final Thoughts

These pro tips will take your checkout page from good to great! Implementing even a few of these ideas can significantly improve user experience, reduce cart abandonment, and increase sales. Remember to continuously test, analyze, and iterate to keep your checkout page optimized for success. 💳✨

Keep your curiosity going.Explore more WordPress →
287 TUTORIALS · 22 TOPICSREADY