Neil Matthews

Category: Customisation

  • Creating a Custom Email in WooCommerce

    Creating a Custom Email in WooCommerce

    WooCommerce is a powerful and flexible e-commerce platform built on WordPress. Customizing it to suit your specific needs can be a game-changer for your online business. One such customization is creating custom email notifications to send to your vendors. This can be useful for order notifications, updates, or any specific information that needs to be communicated to your vendors.

    In this blog post, we will walk through the steps to create a custom email in WooCommerce to send to a vendor. We will cover the following:

    1. Setting up the custom email class.
    2. Registering the custom email with WooCommerce.
    3. Triggering the email based on specific events.

    Step 1: Setting Up the Custom Email Class

    The first step is to create a custom email class. This class will define the content and behavior of the email. Place this code in your theme’s functions.php file or a custom plugin.

    if ( ! class_exists( 'WC_Vendor_Email' ) ) {
        class WC_Vendor_Email extends WC_Email {
    
            public function __construct() {
                $this->id = 'wc_vendor_email';
                $this->title = 'Vendor Email';
                $this->description = 'This email is sent to the vendor when a new order is placed.';
                $this->heading = 'New Order Notification';
                $this->subject = 'New Order Received';
    
                $this->template_html  = 'emails/vendor-email.php';
                $this->template_plain = 'emails/plain/vendor-email.php';
    
                add_action( 'woocommerce_order_status_completed_notification', array( $this, 'trigger' ) );
    
                parent::__construct();
            }
    
            public function trigger( $order_id ) {
                if ( ! $order_id ) return;
    
                $this->object = wc_get_order( $order_id );
                $this->recipient = '[email protected]'; // Replace with the vendor's email address
    
                if ( ! $this->is_enabled() || ! $this->get_recipient() ) {
                    return;
                }
    
                $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
            }
    
            public function get_content_html() {
                return wc_get_template_html( $this->template_html, array(
                    'order'         => $this->object,
                    'email_heading' => $this->get_heading(),
                    'sent_to_admin' => false,
                    'plain_text'    => false,
                    'email'         => $this,
                ) );
            }
    
            public function get_content_plain() {
                return wc_get_template_html( $this->template_plain, array(
                    'order'         => $this->object,
                    'email_heading' => $this->get_heading(),
                    'sent_to_admin' => false,
                    'plain_text'    => true,
                    'email'         => $this,
                ) );
            }
    
        }
    }

    Step 2: Registering the Custom Email with WooCommerce

    Next, we need to register our custom email with WooCommerce. This will make WooCommerce aware of the new email class we just created. Add the following code to the same file where you defined the custom email class.

    add_filter( 'woocommerce_email_classes', 'register_vendor_email' );
    function register_vendor_email( $email_classes ) {
        $email_classes['WC_Vendor_Email'] = include( 'path/to/WC_Vendor_Email.php' ); // Adjust the path as needed
        return $email_classes;
    }

    Step 3: Triggering the Email Based on Specific Events

    In our custom email class, we added a trigger to send the email when an order is completed. This is done using the woocommerce_order_status_completed_notification hook. If you want to trigger the email based on different events, you can change the hook accordingly.

    For example, to trigger the email when an order is placed, you can use the woocommerce_thankyou hook.

    add_action( 'woocommerce_thankyou', 'trigger_vendor_email', 10, 1 );
    function trigger_vendor_email( $order_id ) {
        $email = WC()->mailer()->emails['WC_Vendor_Email'];
        $email->trigger( $order_id );
    }

    Customizing the Email Template

    Finally, you need to create the email templates. Place the HTML and plain text templates in your theme’s WooCommerce email directory (your-theme/woocommerce/emails/).

    HTML Template (vendor-email.php):

    <?php
    if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
    
    echo $email_heading . "\n\n";
    
    echo '<p>Dear Vendor,</p>';
    echo '<p>You have received a new order. Here are the details:</p>';
    
    // Include order details template
    wc_get_template( 'emails/email-order-details.php', array( 'order' => $order ) );
    
    echo '<p>Best regards,</p>';
    echo '<p>Your Company</p>';
    
    echo $email_footer;
    ?>

    Plain Text Template (plain/vendor-email.php):

    <?php
    if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
    
    echo $email_heading . "\n\n";
    
    echo "Dear Vendor,\n";
    echo "You have received a new order. Here are the details:\n\n";
    
    // Include order details template
    wc_get_template( 'emails/plain/email-order-details.php', array( 'order' => $order ) );
    
    echo "Best regards,\n";
    echo "Your Company\n";
    
    echo $email_footer . "\n";
    ?>

    Conclusion

    By following these steps, you can create a custom email in WooCommerce to send notifications to your vendors. This customization can improve communication and streamline processes in your e-commerce store. Remember to test your custom email thoroughly to ensure it works as expected.

    Feel free to modify the code and templates to fit your specific needs. Happy coding!

  • How to Add an Additional Product to the Cart if a Certain Product is Present in WooCommerce

    How to Add an Additional Product to the Cart if a Certain Product is Present in WooCommerce

    In WooCommerce, there are times when you might want to automatically add an additional product to the cart when a specific product is added. This is often referred to as a “forced sell.” In this blog post, we will walk you through how to achieve this using WooCommerce hooks and custom code.

    Step-by-Step Guide

    Prerequisites

    • A running WooCommerce store.
    • Basic knowledge of PHP and WordPress/WooCommerce hooks.

    Step 1: Identify Product IDs

    First, you need to know the IDs of both the primary product and the additional product you want to add to the cart. You can find the product IDs by going to the WooCommerce Products page and hovering over the product names.

    Step 2: Add Custom Code to Your Theme

    We will add the custom code to the functions.php file of your active theme. You can access this file via the WordPress admin dashboard or using FTP.

    Step 3: Write the Code

    Below is the code to automatically add an additional product to the cart when a specific product is added:

    // Add additional product to the cart if a certain product is present
    function add_forced_sell_product( $cart_item_data, $product_id, $variation_id ) {
        // Set the product ID of the primary product
        $target_product_id = 123; // Replace 123 with your primary product ID
    
        // Set the product ID of the additional product
        $additional_product_id = 456; // Replace 456 with your additional product ID
    
        // Check if the primary product is being added to the cart
        if ( $product_id == $target_product_id ) {
            // Check if the additional product is already in the cart
            $found = false;
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( $cart_item['product_id'] == $additional_product_id ) {
                    $found = true;
                    break;
                }
            }
    
            // If the additional product is not found, add it to the cart
            if ( ! $found ) {
                WC()->cart->add_to_cart( $additional_product_id );
            }
        }
    
        return $cart_item_data;
    }
    add_filter( 'woocommerce_add_cart_item_data', 'add_forced_sell_product', 10, 3 );

    Step 4: Save and Test

    After adding the code, save the functions.php file and test your WooCommerce store:

    1. Add the primary product (with the ID you specified) to your cart.
    2. Check the cart to see if the additional product is automatically added.

    Explanation of the Code

    • Hooking into the Cart Process: We use the woocommerce_add_cart_item_data filter to hook into the process of adding items to the cart.
    • Product IDs: We set the target product ID (the product that triggers the addition) and the additional product ID (the product to be added).
    • Cart Check: When the target product is added to the cart, we check if the additional product is already in the cart.
    • Add Product: If the additional product is not already in the cart, we add it using the add_to_cart method.

    Conclusion

    By following these steps, you can easily set up a forced sell in WooCommerce, where adding a specific product to the cart automatically adds another product. This approach can be customized further to meet various business requirements, such as adding multiple products, applying conditions, or modifying quantities.

    Feel free to leave a comment below if you have any questions or need further assistance!

    Happy coding!

  • Adding Custom Shipping to WooCommerce Checkout for Specific Products

    Adding Custom Shipping to WooCommerce Checkout for Specific Products

    Adding custom shipping methods to the WooCommerce checkout process can be essential for tailoring shipping options to specific products. This blog post will guide you through the process of adding a custom shipping method when a particular product is in the cart using WooCommerce hooks and filters.

    Step-by-Step Guide

    Prerequisites

    • A running WooCommerce store.
    • Basic knowledge of PHP and WordPress/WooCommerce hooks.

    Step 1: Identify the Product ID

    First, you need to know the ID of the product for which you want to add custom shipping. You can find the product ID by going to the WooCommerce Products page and hovering over the product name.

    Step 2: Add Custom Code to Your Theme

    We will add the custom code to the functions.php file of your active theme. You can access this file via the WordPress admin dashboard or using FTP.

    Step 3: Write the Code

    Below is the code to add a custom shipping method when a specific product is in the cart:

    // Add custom shipping method for specific product in WooCommerce
    function add_custom_shipping_method( $available_methods ) {
        global $woocommerce;
    
        // Set the product ID for which the custom shipping should be applied
        $target_product_id = 123; // Replace 123 with your product ID
    
        // Loop through the cart items
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( $cart_item['product_id'] == $target_product_id ) {
                // Define the custom shipping method
                $custom_shipping_method = array(
                    'custom_shipping' => array(
                        'id'    => 'custom_shipping',
                        'label' => __( 'Custom Shipping', 'woocommerce' ),
                        'cost'  => '10.00', // Set the custom shipping cost
                    ),
                );
    
                // Merge custom shipping method with available methods
                $available_methods = array_merge( $available_methods, $custom_shipping_method );
                break; // No need to add the shipping method more than once
            }
        }
    
        return $available_methods;
    }
    add_filter( 'woocommerce_package_rates', 'add_custom_shipping_method' );

    Step 4: Save and Test

    After adding the code, save the functions.php file and test your WooCommerce checkout process:

    1. Add the specific product (with the ID you specified) to your cart.
    2. Proceed to the checkout page.
    3. You should see the custom shipping method applied to the order.

    Explanation of the Code

    • Hooking into the Shipping Methods: We use the woocommerce_package_rates filter to add our custom shipping method to the available shipping methods.
    • Product ID and Shipping Cost: We set the target product ID and the custom shipping cost.
    • Cart Loop: We loop through the cart items to check if the target product is in the cart.
    • Define Custom Shipping Method: If the target product is found, we define the custom shipping method with its ID, label, and cost.
    • Merge Shipping Methods: We merge the custom shipping method with the existing available shipping methods.

    Conclusion

    By following these steps, you can easily add a custom shipping method to the WooCommerce checkout process for specific products. This approach can be extended and customized further to meet various business requirements, such as applying different shipping methods based on product categories, quantities, or customer locations.

    Feel free to leave a comment below if you have any questions or need further assistance!

    Happy coding!

  • Adding a Custom Fee to WooCommerce Checkout for Specific Products

    Adding a Custom Fee to WooCommerce Checkout for Specific Products

    Adding custom fees to the WooCommerce checkout process can be a powerful way to handle additional charges for specific products. This blog post will guide you through adding a custom fee when a particular product is in the cart using WooCommerce hooks and filters.

    Step-by-Step Guide

    Prerequisites

    • A running WooCommerce store.
    • Basic knowledge of PHP and WordPress/WooCommerce hooks.

    Step 1: Identify the Product ID

    First, you need to know the ID of the product for which you want to add a custom fee. You can find the product ID by going to the WooCommerce Products page and hovering over the product name.

    Step 2: Add Custom Code to Your Theme

    We will add the custom code to the functions.php file of your active theme. You can access this file via the WordPress admin dashboard or using FTP.

    Step 3: Write the Code

    Below is the code to add a custom fee when a specific product is in the cart:

    // Add custom fee for specific product in WooCommerce
    function add_custom_fee_for_specific_product( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
            return;
        }
    
        // Set the product ID for which the custom fee should be applied
        $target_product_id = 123; // Replace 123 with your product ID
        $fee_amount = 10; // Set the custom fee amount
    
        // Loop through the cart items
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Check if the target product is in the cart
            if ( $cart_item['product_id'] == $target_product_id ) {
                // Add the custom fee
                $cart->add_fee( __( 'Custom Fee', 'woocommerce' ), $fee_amount );
                break; // No need to add the fee more than once
            }
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'add_custom_fee_for_specific_product' );

    Step 4: Save and Test

    After adding the code, save the functions.php file and test your WooCommerce checkout process:

    1. Add the specific product (with the ID you specified) to your cart.
    2. Proceed to the checkout page.
    3. You should see the custom fee applied to the order.

    Explanation of the Code

    • Hooking into the Checkout Process: We use the woocommerce_cart_calculate_fees hook to add our custom fee logic during the cart calculation.
    • Admin Check: The code first checks if the current request is an admin request and not an AJAX request to avoid unnecessary execution.
    • Product ID and Fee Amount: We set the target product ID and the custom fee amount.
    • Cart Loop: We loop through the cart items to check if the target product is in the cart.
    • Add Fee: If the target product is found, we add the custom fee using the add_fee method.

    Conclusion

    By following these steps, you can easily add a custom fee to the WooCommerce checkout process for specific products. This approach can be extended and customized further to meet various business requirements, such as applying different fees based on product categories, quantities, or customer roles.

    Feel free to leave a comment below if you have any questions or need further assistance!

    Happy coding!

  • Enhancing User Engagement: Change the WooCommerce Add to Cart Label to “Login” for Non-Logged-In Users

    Enhancing User Engagement: Change the WooCommerce Add to Cart Label to “Login” for Non-Logged-In Users

    Introduction – Change the WooCommerce Add to Cart Label to “Login” for Non-Logged-In Users
    Creating a personalized and seamless shopping experience is crucial for the success of your online store. WooCommerce, the renowned WordPress plugin for e-commerce, offers extensive customization options to tailor your website. If you’re looking to encourage non-logged-in users to create an account or log in, changing the “Add to Cart” label to “Login” can be an effective strategy. In this blog post, we’ll guide you through the process of modifying the label and adding a link to the login page, elevating user engagement and potentially boosting conversions.

    Step-by-Step Guide to Changing the “Add to Cart” Label to “Login” and Adding a Login Page Link:

    Step 1: Access Your WordPress Dashboard:
    Log in to your WordPress admin panel using your credentials. Once logged in, navigate to the “Plugins” tab and click on “Add New.” Search for the “Code Snippets” plugin and install it. This plugin allows you to add custom code snippets without directly modifying your theme files.

    Step 2: Create a New Code Snippet:
    After installing and activating the “Code Snippets” plugin, access the “Snippets” section from the WordPress sidebar menu. Click on “Add New” to create a new code snippet.

    Step 3: Add the Custom Code:
    In the code snippet editor, provide a descriptive title for your snippet, such as “Change Add to Cart Label to Login with Login Page Link.” Copy and paste the following code into the code box:

    add_filter('woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_label');
    add_filter('woocommerce_product_add_to_cart_text', 'change_add_to_cart_label');
    
    function change_add_to_cart_label($label) {
        if (!is_user_logged_in()) {
            $login_url = wp_login_url(get_permalink());
            $label = '<a href="' . $login_url . '">' . __('Login', 'woocommerce') . '</a>';
        }
        return $label;
    }

    This code utilizes two WooCommerce filters, ‘woocommerce_product_single_add_to_cart_text’ and ‘woocommerce_product_add_to_cart_text’, to modify the label of the “Add to Cart” button. It also includes the login page link to redirect non-logged-in users to the appropriate page.

    Step 4: Save and Activate the Code Snippet:
    Once you have added the code, click on the “Save Changes and Activate” button to save the snippet and activate it on your website.

    Step 5: Test the Modifications:
    To see the changes in action, visit your product pages while logged out or using an incognito browser window. The “Add to Cart” button should now display “Login” as a clickable link. Clicking on the link will redirect non-logged-in users to the login page.

    Conclusion – Change the WooCommerce Add to Cart Label to “Login” for Non-Logged-In Users
    By changing the “Add to Cart” label to “Login” and adding a login page link, you can encourage non-logged-in users to create an account or log in, enhancing their engagement with your WooCommerce store. Utilizing the “Code Snippets” plugin simplifies the process, ensuring that your theme files remain intact. Customize your online store, elevate user engagement, and potentially boost conversions by implementing this straightforward modification. Embrace the power of personalization and create a seamless shopping experience for your customers.

    Click here to learn more about the Code Snippets plugin

    If you need custom code snippets for your WooCommece store, that’s something we can do as part of your WooCommerce support plan.

    Photo by Micah Williams on Unsplash

  • How To Add WordPress Code Snippets The Easy Way

    How To Add WordPress Code Snippets The Easy Way

    In this video post I want to show you how to add code snippets the easy way to your WordPress site.

    You’ve probably seen recommendations to add code to your functions.php file to fix an errors on your site, to add functionality or to make a change of some sort.

    You will be presented with a wall of php code and you are told to add this to your functions.php file.  All well and good if you are a developer but what if you are not that technical and don’t want to mess with code files.

    There are some issues with “simply adding code to functions.php”, here is what you need to be aware of:

    • If there are errors in the code, you can crash your site.
    • When you change your theme the code also needs to be migrated.
    • A site with lots of snippets can become a pain to manage and remember what each piece of code does

    Video Demo – How To Add WordPress Code Snippets The Easy Way

    In this demo I’ll show you how to use this plugin to add code

    The Plugin

    Here’s a link to the plugin I used
    https://en-gb.wordpress.org/plugins/code-snippets/

    The Code Snippet

    And if you want to change your add to cart button to buy now, here is the code.
    // To change add to cart text on single product page add_filter( 'woocommerce_product_single_add_to_cart_text', 'woocommerce_custom_single_add_to_cart_text' ); function woocommerce_custom_single_add_to_cart_text() { return __( 'Buy Now', 'woocommerce' ); }

    Wrap Up – How To Add WordPress Code Snippets The Easy Way

    To wrap up this plugin is great when you are developing a site and need to manage lots of custom code, and not have it break your site during testing.

    A highly customised site with lots of snippets can become messy when a few months later you cannot remember what each piece of code does, so descriptions and tagging make things much easier to maintain.

    If you are still not happy adding custom code to your WordPress site you can always hire me to do it for you.

    Photo by Alexander Sinn on Unsplash

  • How To Add WordPress Code Snippets The Easy Way

    How To Add WordPress Code Snippets The Easy Way

    In this video post I want to show you how to add code snippets the easy way to your WordPress site.

    You’ve probably seen recommendations to add code to your functions.php file to fix an errors on your site, to add functionality or to make a change of some sort.

    You will be presented with a wall of php code and you are told to add this to your functions.php file.  All well and good if you are a developer but what if you are not that technical and don’t want to mess with code files.

    There are some issues with “simply adding code to functions.php”, here is what you need to be aware of:

    • If there are errors in the code, you can crash your site.
    • When you change your theme the code also needs to be migrated.
    • A site with lots of snippets can become a pain to manage and remember what each piece of code does

    Video Demo – How To Add WordPress Code Snippets The Easy Way

    In this demo I’ll show you how to use this plugin to add code

    The Plugin

    Here’s a link to the plugin I used
    https://en-gb.wordpress.org/plugins/code-snippets/

    The Code Snippet

    And if you want to change your add to cart button to buy now, here is the code.
    // To change add to cart text on single product page add_filter( 'woocommerce_product_single_add_to_cart_text', 'woocommerce_custom_single_add_to_cart_text' ); function woocommerce_custom_single_add_to_cart_text() { return __( 'Buy Now', 'woocommerce' ); }

    Wrap Up – How To Add WordPress Code Snippets The Easy Way

    To wrap up this plugin is great when you are developing a site and need to manage lots of custom code, and not have it break your site during testing.

    A highly customised site with lots of snippets can become messy when a few months later you cannot remember what each piece of code does, so descriptions and tagging make things much easier to maintain.

    If you are still not happy adding custom code to your WordPress site you can always hire me to do it for you.

    Photo by Alexander Sinn on Unsplash