Category: Wordpress

  • How to create custom fields in WooCommerce checkout form?

    How to create custom fields in WooCommerce checkout form?

    Creating custom fields in the checkout process of a WooCommerce store can enhance the user experience by collecting additional, relevant information from customers. Here’s a step-by-step guide on how to do this using hooks in WooCommerce, without a plugin. If you prefer a plugin, I can guide you through that process as well.

    Step 1: Add the Custom Fields to Checkout Page

    You need to add the custom fields to the WooCommerce checkout page. This can be done by hooking into WooCommerce’s actions. Add the following code to your theme’s functions.php file or a custom plugin:

    add_action('woocommerce_after_order_notes', 'custom_checkout_field');
    
    function custom_checkout_field($checkout) {
        echo '<div id="custom_checkout_field"><h2>' . __('My Custom Field') . '</h2>';
    
        woocommerce_form_field('my_custom_field', array(
            'type'          => 'text',
            'class'         => array('my-custom-field-class form-row-wide'),
            'label'         => __('Enter your data'),
            'placeholder'   => __('Enter something'),
            'required'      => true,
            ), $checkout->get_value('my_custom_field'));
    
        echo '</div>';
    }

    Step 2: Validate the Custom Field

    You should ensure that the data entered into the custom fields is valid. Add the following code to handle validation:

    add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
    
    function custom_checkout_field_process() {
        // Check if set, if its not set add an error.
        if (!$_POST['my_custom_field'] || trim($_POST['my_custom_field']) == '') {
            wc_add_notice(__('My Custom Field is a required field.'), 'error');
        }
    }

    Step 3: Save the Custom Field Value

    Once the field is validated, you need to save the custom field value. This value can be saved in the order meta:

    add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta');
    
    function custom_checkout_field_update_order_meta($order_id) {
        if (!empty($_POST['my_custom_field'])) {
            update_post_meta($order_id, 'My Custom Field', sanitize_text_field($_POST['my_custom_field']));
        }
    }

    Step 4: Display the Custom Field Value in the Admin Order Panel

    To view this custom field in the order edit pages in the admin panel, add the following code:

    add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1);
    
    function my_custom_checkout_field_display_admin_order_meta($order) {
        echo '<p><strong>' . __('My Custom Field') . ':</strong> ' . get_post_meta($order->get_id(), 'My Custom Field', true) . '</p>';
    }

    Additional Customizations

    • You can change the type of the field (text, checkbox, select, etc.) in the woocommerce_form_field function call.
    • Modify the placement of the field by hooking into different actions.
    • Use CSS to style the fields as needed.

    This example covers adding a simple text field. You can extend this by adding multiple fields, different types of fields, and more complex validation logic. Always test changes on a development site before applying them to your live store to avoid disrupting the shopping experience.

    Jassa

    Thanks

  • How to offer shipping on products but local pickup only in WooCommerce?

    How to offer shipping on products but local pickup only in WooCommerce?

    Setting up different delivery options for specific products in WooCommerce involves using conditional logic to control shipping methods based on the products in the cart. Here’s a step-by-step guide on how to offer shipping for one product and local pickup only for another within WooCommerce:

    Step 1: Set Up Shipping Zones

    First, you need to configure your shipping zones and methods in WooCommerce:

    1. Go to WooCommerce > Settings > Shipping in your WordPress dashboard.
    2. Add a Shipping Zone and name it (e.g., “Domestic” for local shipping).
    3. Add Shipping Methods to this zone. You’ll likely want to add both ‘Flat Rate’ and ‘Local Pickup’. You can configure these based on your needs.

    Step 2: Install a Plugin for Conditional Shipping

    Since WooCommerce by default doesn’t allow you to disable shipping methods based on specific products directly, you’ll need a plugin that can handle conditional logic for shipping. Here are a couple of popular options:

    • WooCommerce Conditional Shipping and Payments: This plugin allows you to create conditions for shipping methods and payment gateways based on various factors, including product, category, cart subtotal, and more.
    • Table Rate Shipping by WooCommerce (if you need more detailed shipping rules based on weight, items, etc.).

    Step 3: Configure the Plugin

    Once you have installed your chosen plugin, configure it to set up conditions for your products:

    Using WooCommerce Conditional Shipping and Payments

    1. Go to WooCommerce > Settings > Conditional Shipping and Payments.
    2. Add a New Condition. Here, you can specify conditions such as:
    • If Product A is in the cart, enable ‘Flat Rate’.
    • If Product B is in the cart, disable ‘Flat Rate’ and enable only ‘Local Pickup’.

    Step 4: Test Your Setup

    • Add Product A to the cart and check if both shipping and pickup options are available.
    • Add Product B to the cart and check if only the local pickup is available.

    Make sure to test various combinations of products to ensure that the conditions work as expected. Testing in a staging environment before going live is also a good practice to avoid disrupting your live store.

    Optional: Customize Further with Code

    If you’re comfortable with coding or have access to a developer, you can also achieve this functionality by adding custom functions to your theme’s functions.php file. This method requires a good understanding of PHP and WooCommerce hooks.

    Here’s a basic example of how you might code this:

    function custom_override_shipping_methods($available_methods) {
        global $woocommerce;
        $specific_product_id = 123;  // ID of the product that should only have local pickup
    
        // Check if the specific product is in the cart
        foreach($woocommerce->cart->cart_contents as $key => $values) {
            if($values['product_id'] == $specific_product_id) {
                // Remove all methods except local pickup
                foreach($available_methods as $method_id => $method) {
                    if($method_id !== 'local_pickup:1') {  // Ensure the correct ID for local pickup
                        unset($available_methods[$method_id]);
                    }
                }
                break;
            }
        }
    
        return $available_methods;
    }
    add_filter('woocommerce_package_rates', 'custom_override_shipping_methods', 100);

    This code checks if a specific product is in the cart and, if so, removes all shipping methods except local pickup.

    Final Thoughts

    Using a plugin is the easiest and most flexible approach for most users, especially those who prefer not to edit code. If your needs grow more complex, consider hiring a developer to customize your WooCommerce store to precisely match your business requirements.

  • Implementing product visibility based on user role along with time scheduling in WooCommerce

    Implementing product visibility based on user role along with time scheduling in WooCommerce

    Implementing product visibility based on user role along with time scheduling in WooCommerce involves customizing how and when products are displayed to different user roles on your WordPress site. You’ll need to use hooks and filters provided by WooCommerce and possibly some custom programming to manage the visibility of products based on both the user’s role and specific time constraints.

    Here’s a step-by-step approach to achieve this:

    Implementing product visibility based on user role along with time scheduling in WooCommerce
    Implementing product visibility based on user role along with time scheduling in WooCommerce

    1. Install Necessary Plugins

    Before starting, ensure you have the WooCommerce plugin installed and activated. For role management, you might consider using a plugin like “Groups” or “User Role Editor” to define or modify user roles and capabilities.

    2. Custom Plugin for Role-Based Visibility

    Create a custom WordPress plugin to handle the role-based visibility logic. This will include checking the user’s role and the current time to determine if a product should be visible.

    Here’s a simple example of how you can start:

    a. Create a new plugin

    Create a new folder in your wp-content/plugins directory, name it something relevant like woocommerce-role-time-based-visibility.

    Inside this folder, create a file named woocommerce-role-time-based-visibility.php and add the following plugin header:

    <?php
    /*
    Plugin Name: WooCommerce Role-Time Based Visibility
    Description: Controls the visibility of products based on user roles and specific time schedules.
    Version: 1.0
    Author: Your Name
    */
    
    // Your code goes here

    b. Hook into WooCommerce Product Query

    Use the woocommerce_product_query hook to modify the product query based on the user’s role and the current time.

    add_action('woocommerce_product_query', 'filter_products_by_role_and_time');
    function filter_products_by_role_and_time($query) {
        $current_user = wp_get_current_user();
        $current_time = current_time('H:i');
    
        // Example: Hide certain products for 'customer' role from 20:00 to 08:00
        if (in_array('customer', (array) $current_user->roles)) {
            if ($current_time > '20:00' || $current_time < '08:00') {
                $query->set('tax_query', array(array(
                    'taxonomy' => 'product_visibility',
                    'field'    => 'name',
                    'terms'    => array('exclude-from-catalog'),
                    'operator' => 'IN'
                )));
            }
        }
    }

    This code snippet checks if the current user has the ‘customer’ role and if the current time is between 8 PM and 8 AM. If both conditions are true, it modifies the product query to hide products that are marked as ‘exclude-from-catalog’.

    3. Use Meta Data to Manage Time Conditions

    You may want to use product meta fields to set visibility times for each product. This can be managed via the product edit page in the admin area. You would then modify the above code to retrieve and compare these meta values instead of using hard-coded times.

    4. Testing

    After implementing the code, you need to thoroughly test your WooCommerce store to ensure that products are being shown or hidden correctly based on user roles and the specified times.

    5. Consider Caching

    Be aware that caching mechanisms might interfere with dynamic visibility changes. If your site uses caching, make sure it is configured to handle these dynamic changes, or disable caching for product pages if necessary.

    By following these steps, you should be able to control product visibility in WooCommerce based on user roles and specific time schedules. This requires a fair amount of custom coding, so if you’re not comfortable with PHP and WordPress development, consider hiring a developer.

    Jassa

    Thanks

  • How to add a 20% increase to the product pricing in WooCommerce?

    How to add a 20% increase to the product pricing in WooCommerce?

    To add a 20% increase to the product pricing in WooCommerce, you can use a hook in your theme’s functions.php file or in a custom plugin. This involves manipulating the price display using WooCommerce hooks, particularly focusing on altering the product prices dynamically.

    How to add a 20% increase to the product pricing in WooCommerce?
    How to add a 20% increase to the product pricing in WooCommerce?

    Here’s how you can achieve this by adding a snippet of PHP code to adjust the prices:

    1. Open your WordPress theme’s functions.php file: This file is located in your theme’s directory. You can access it through the WordPress admin panel under Appearance > Theme Editor, or you can use an FTP client to open the file directly from your server.
    2. Add the following code snippet: This code uses the woocommerce_get_price_html filter to modify the displayed price of all products by adding 20% to their original price.
    add_filter('woocommerce_get_price_html', 'increase_product_price_by_twenty_percent', 10, 2);
    
    function increase_product_price_by_twenty_percent($price, $product) {
        // Check if the product has a price, to avoid errors with products that do not have pricing set
        if ($product->get_price()) {
            $original_price = floatval($product->get_price()); // Get the original price
            $increased_price = $original_price * 1.20; // Increase price by 20%
    
            // Format the increased price based on WooCommerce settings and return
            $price = wc_price($increased_price);
        }
        return $price;
    }

    Explanation:

    • The woocommerce_get_price_html filter is used to alter the HTML price output on the product pages, shop pages, etc.
    • This code gets the product’s original price, increases it by 20%, and then formats it using WooCommerce’s wc_price() function, which ensures that it adheres to the settings you have for currency formatting in WooCommerce.

    Important Notes:

    • This change affects only how prices are displayed on the website. It does not change how prices are stored in the database or the prices used during checkout. If you need to alter the actual prices (not just how they are displayed), you might need a different approach involving the cart and checkout process.
    • Always backup your website before making changes to the code.
    • Test this change on a staging environment before applying it to your live website to avoid any potential issues with your live store.

    This customization will effectively display all product prices with a 20% increase throughout your WooCommerce store.

  • Exclude a specific shipping class from qualifying for free shipping in WooCommerce

    Exclude a specific shipping class from qualifying for free shipping in WooCommerce

    woocommerce free shipping exclude for some classes, Hide other shipping methods when “Free Shipping” is available, Hide free shipping for specific shipping classes exclusively in Woocommerce.


    To exclude a specific shipping class, such as one for bulky items, from qualifying for free shipping in WooCommerce, you can modify the settings for the free shipping method. Here’s how to adjust your WooCommerce settings to ensure that orders containing bulky items do not qualify for free shipping:

    1. Log in to your WordPress dashboard. Navigate to your website’s admin area.
    2. Go to WooCommerce settings. On the left sidebar, hover over “WooCommerce” and click on “Settings.”
    3. Access the Shipping tab. This is where you manage all your shipping settings.
    4. Select the appropriate shipping zone. Click on the shipping zone where you’ve set up free shipping.
    5. Edit the free shipping method. Click on the “Free Shipping” method you previously created to edit its settings.
    6. Adjust the free shipping requirements. In the settings for free shipping:
    • In the “Free Shipping Requires…” dropdown, choose “A valid free shipping coupon / A minimum order amount / A minimum order amount OR a coupon.”
    • Ensure you have set the minimum order amount as needed (e.g., £30).
    1. Use shipping classes to exclude bulky items:
    • First, ensure you have a shipping class created for bulky items. Go to WooCommerce > Settings > Shipping > Shipping classes and make sure there’s a class labeled appropriately (e.g., “Bulky”).
    • Then, go back to the shipping zone settings and click on “Edit” under the Free Shipping method.
    • Look for an option to exclude shipping classes from free shipping. WooCommerce by default does not offer an explicit option to exclude classes directly from the free shipping method settings. If such an option is not visible, you will need to add custom code to your site.
    1. Add custom code to function.php: If WooCommerce’s default options don’t support excluding shipping classes directly, you can add the following custom code to your theme’s functions.php file:
    function disable_free_shipping_for_bulky($is_available, $package) {
        // Define the shipping class you want to exclude
        $excluded_class = 'bulky'; // Use the slug of your bulky shipping class
    
        // Check each item in the cart
        foreach ($package['contents'] as $item) {
            if ($item['data']->get_shipping_class() == $excluded_class) {
                return false; // Free shipping is not available
            }
        }
    
        return $is_available;
    }
    add_filter('woocommerce_shipping_free_shipping_is_available', 'disable_free_shipping_for_bulky', 10, 2);

    Replace 'bulky' with the actual slug of the shipping class for bulky items in your WooCommerce setup.

    1. Save changes and test. After adding the custom code, make sure to test the checkout process to ensure that the free shipping option does not appear when a cart contains items from the bulky shipping class.

    By using these steps, you can effectively exclude orders containing bulky items from qualifying for free shipping in your WooCommerce store.

    Thanks

    Jassa

  • Woocommerce apply coupon programmatically on cheapest product in cart

    Woocommerce apply coupon programmatically on cheapest product in cart

    Apply Coupon Programmatically woocommerce, WooCommerce before apply coupon hook, Woocommerce apply coupon ajax, WooCommerce add discount to cart programmatically, Woocommerce apply coupon programmatically on cheapest product in cart code


    To programmatically apply a coupon to the cheapest product in the cart in a WooCommerce store, you can achieve this by using WooCommerce hooks and custom PHP code. Below is a step-by-step guide and code example on how to set this up.


    Step 1: Create a Custom Coupon

    First, you’ll need to create a coupon in WooCommerce. You can do this from the WordPress admin dashboard:

    • Go to WooCommerce > Coupons.
    • Create a new coupon, choose a discount type, and configure any other settings you need.
    • Note the coupon code as you will use it in the code.

    Guys if you are new in WordPress or in WooCommerce then please check the below links for some good tutorials:

    Step 2: Add Custom PHP Code

    Add the following code to your theme’s functions.php file or a custom plugin. This code will find the cheapest product in the cart and apply the coupon only to that product.

    function apply_coupon_to_cheapest_item() {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $coupon_code = 'YOUR_COUPON_CODE'; // Replace 'YOUR_COUPON_CODE' with your actual coupon code
    
        if ( WC()->cart ) {
            $cart = WC()->cart;
            $items = $cart->get_cart();
            $minimum_price = null;
            $cheapest_item_key = null;
    
            // Determine the cheapest item in the cart
            foreach ( $items as $item_key => $item ) {
                if ( is_null( $minimum_price ) || $item['line_total'] < $minimum_price ) {
                    $minimum_price = $item['line_total'];
                    $cheapest_item_key = $item_key;
                }
            }
    
            if ( $cheapest_item_key !== null ) {
                // Apply the coupon only to the cheapest item
                foreach ( $cart->get_applied_coupons() as $code ) {
                    $cart->remove_coupon( $code ); // Remove all coupons
                }
                $cart->set_quantity( $cheapest_item_key, 1, false ); // Temporarily adjust quantity to ensure discount applies only to one item
                $cart->apply_coupon( $coupon_code );
                $cart->set_quantity( $cheapest_item_key, $items[$cheapest_item_key]['quantity'], false ); // Reset quantity
            }
        }
    }
    
    add_action( 'woocommerce_before_calculate_totals', 'apply_coupon_to_cheapest_item' );

    Explanation

    • Step 1: The code checks if the cart exists.
    • Step 2: It then iterates over the items in the cart to find the cheapest item.
    • Step 3: After determining the cheapest item, the code removes any existing coupons, adjusts the quantity of the cheapest item to one, applies the coupon, and then resets the quantity.

    Important Notes

    • This approach assumes that the coupon can be applied to any product. Make sure your coupon conditions in the WooCommerce settings allow this.
    • Testing is crucial. Test this code in a staging environment before using it on a live site to ensure it behaves as expected.
    • Adjust the code as necessary, especially if your WooCommerce setup has special pricing rules or other customizations.

    This implementation should give you a good starting point for applying a coupon programmatically to the cheapest product in the WooCommerce cart.

    Thanks

    Jassa

  • Woocommerce Instagram shop for vendors

    Woocommerce Instagram shop for vendors

    If you’re looking to set up an Instagram shop for vendors on a WooCommerce Dokan website, there are a few steps you’ll need to follow. This integration allows you to feature and sell products directly through Instagram, making it easier for customers to shop your items right from their feeds. Here’s how you can get started:

    1. Ensure Compliance with Instagram Requirements:
    • Your business must comply with Instagram’s merchant agreement and commerce policies.
    • Your Instagram account must be converted into a business account.
    • You need to have a Facebook Page connected to your business Instagram account since Instagram shops require integration with Facebook.
    1. Set Up WooCommerce:
    • Your WooCommerce store should be properly set up and configured on your website. Make sure your products are categorized and have all the necessary information such as descriptions, prices, and images.
    1. Connect WooCommerce to Facebook:
    • Use a plugin like Facebook for WooCommerce. This plugin connects your WooCommerce store to Facebook and allows you to synchronize your products to a Facebook catalog.
    • Set up the Facebook catalog by integrating it with your business’s Facebook page. This catalog will then be used to feature products on Instagram.
    1. Enable Instagram Shopping:
    • Once your Facebook catalog is set up and populated with your WooCommerce products, connect this catalog to your Instagram business profile.
    • Apply for Instagram Shopping through the Instagram app by going to Settings, then Business, and selecting Shopping. This process may require review from Instagram, which can take a few days.
    1. Tag Products on Instagram:
    • After getting approval from Instagram, you can start tagging products in your Instagram posts and stories. Users can tap on these tags to see product details and be directed to your WooCommerce store to make a purchase.
    1. Maintain and Optimize Your Listings:
    • Regularly update your product catalog and keep your inventory, pricing, and product descriptions accurate.
    • Utilize Instagram insights and WooCommerce analytics to understand customer preferences and behavior, which can help in optimizing your marketing and sales strategy.
    1. Promote Your Instagram Shop:
    • Engage with your followers through regular posts, stories, and interactive content.
    • Consider using Instagram ads to reach a broader audience.

    This integration not only enhances the shopping experience by making it more accessible and seamless but also leverages the visual appeal of Instagram to attract customers.

  • How to get current logged in user using WordPress Rest Api?

    How to get current logged in user using WordPress Rest Api?

    Hello guys, how are you? Welcome back on blog therichpost.com. To obtain information about the current logged-in user through the WordPress REST API, please follow the below logic guys.

    $user_id = ""; //<- add this
    
    add_action( 'rest_api_init', 'add_custom_users_api');
    
    function add_custom_users_api(){
        $GLOBALS['user_id'] = get_current_user_id(); //<- add this
    
        // route url: domain.com/wp-json/mmw/v1/testing
        register_rest_route( 'mmw/v1', 'testing', array(
            'methods' => 'GET',
            'callback' => 'get_custom_users_data',
        ));
    }
    //Customize the callback to your liking
    function get_custom_users_data(){
        return $GLOBALS['user_id']; //<- add this
    }

    Remember, for security reasons, direct use of admin credentials in scripts or applications is not recommended. Instead, use application passwords or OAuth tokens, which can be revoked if necessary.

    Guys if you will have any kind of query then feel free to comment below.

    Jassa

    Thanks

  • Woocommerce hook change shipping text on checkout page

    Woocommerce hook change shipping text on checkout page

    Hello guys how are you? Welcome back to my channel. Today in this post I am going to show you Woocommerce hook change shipping text on checkout page.

    Guys I have used both latest versions WordPress 6.3 and WooCommerce 8.6.

    Guys if you are new in WordPress or in WooCommerce then please check the below links for some good tutorials:

    1. WooCommerce Hooks
    2. WordPress Tricks
    3. WordPress Hooks
    Woocommerce hook change shipping text on checkout page
    Woocommerce hook change shipping text on checkout page

    Guys here is the working code snippet and please use it carefully:

    1. Guys here is the code snippet and you need to add your theme’s functions.php file:

    add_filter( 'woocommerce_shipping_package_name', 'therichpost_new_shipping_title' );
     
    function therichpost_new_shipping_title() {
       return "Shipping Methods";
    }
    • WooCommerce move coupon field checkout

    This is it guys and if you will have any kind of query, suggestion or requirement then feel free to comment below.

    Jassa

    Developer’s King

    Thanks

  • How to Move coupon form before subtotal in WooCommerce checkout after ajax?

    How to Move coupon form before subtotal in WooCommerce checkout after ajax?

    To move the coupon form before the subtotal in the WooCommerce checkout page, especially after an AJAX update (which occurs when cart items are updated), you’ll need to use a combination of actions and filters provided by WooCommerce, as well as some custom JavaScript to handle the AJAX event.

    Live demo

    Step 1: Remove the Default Coupon Form

    WooCommerce normally displays the coupon form under the order summary. To move it, you first need to remove it from its default location. This can be done by adding the following PHP code to your theme’s functions.php file or a custom plugin:

    function custom_remove_checkout_coupon_form() {
        remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
    }
    add_action( 'woocommerce_before_checkout_form', 'custom_remove_checkout_coupon_form', 9 );

    Step 2: Add the Coupon Form to a New Location

    Next, decide where you want the coupon form to appear. Since you want it before the subtotal, you can hook it to a suitable action hook. Unfortunately, there isn’t a direct hook for “before subtotal” in the WooCommerce checkout form, but you can use the woocommerce_review_order_before_order_total hook as it’s close to the subtotal area. Add the following code:

    function custom_add_checkout_coupon_form() {
        wc_get_template( 'checkout/form-coupon.php', array( 'checkout' => WC()->checkout() ) );
    }
    add_action( 'woocommerce_review_order_before_order_total', 'custom_add_checkout_coupon_form' );

    Step 3: Handle AJAX Updates

    When cart items are updated, WooCommerce uses AJAX to refresh the checkout page, which may affect the placement of the coupon form. To ensure the coupon form stays in the correct location, you can use custom JavaScript to move the form dynamically after AJAX updates.

    Add the following JavaScript code to your theme’s custom.js file or inline within a custom plugin. If your theme doesn’t have a custom.js file, you might need to enqueue one correctly in your theme’s functions.php.

    jQuery(document).ready(function($) {
        // Function to move the coupon form
        function moveCouponForm() {
            var couponForm = $('.checkout_coupon');
            var targetLocation = $('.order-total').closest('tr'); // Adjust this selector based on your theme's structure
            couponForm.insertBefore(targetLocation);
        }
    
        // Initial move
        moveCouponForm();
    
        // Reapply after checkout updates
        $(document).on('updated_checkout', function() {
            moveCouponForm();
        });
    });

    Notes:

    • The JavaScript selector $('.order-total').closest('tr') is used to find the correct place before the subtotal. Depending on your theme or if you have customized the WooCommerce templates, you might need to adjust this selector.
    • Ensure to clear your site and browser cache after applying these changes to see the effect.
    • Test the checkout process to ensure everything works as expected and that applying coupons still functions correctly.

    This approach combines PHP to modify the WooCommerce templates and JavaScript to ensure the UI remains consistent after AJAX updates. It gives you control over where the coupon form appears in the checkout process.