Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Tag: WooCommerce

WooCommerce: Set role‑based pricing (simple example)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Set role‑based pricing (simple example)

WooCommerce: Set Role-Based Pricing (Simple Example)

If you want to offer different product prices to customers based on their user roles in WooCommerce, this guide will help you implement role-based pricing quickly and effectively. By default, WooCommerce does not support pricing variations by user role, but with a small code snippet, you can customize prices for roles like wholesale customers, subscribers, or any custom role.

Quick Fix: How to Set Role-Based Pricing in WooCommerce

  1. Identify the user roles you want to target.
  2. Add a code snippet to your theme’s functions.php or a custom plugin.
  3. Customize the price adjustments in the snippet according to your roles.
  4. Test by logging in as users with different roles to verify prices change accordingly.

Why This Happens

WooCommerce uses a single price field per product by default, which applies universally to all customers. It does not differentiate pricing based on user roles or customer groups out of the box. To offer role-based pricing, you need to programmatically adjust the displayed price depending on the logged-in user’s role. This is commonly needed for wholesale stores, membership discounts, or tiered pricing strategies.

Requirements

  • WooCommerce installed and activated on your WordPress site.
  • Basic knowledge of editing theme files or creating a simple plugin.
  • Access to your site’s file system or WordPress admin editor.
  • Understanding of user roles in WordPress/WooCommerce.

Step-by-Step: Implement Role-Based Pricing in WooCommerce

  1. Backup your site: Always back up your site before editing code.
  2. Access your theme’s functions.php file: Use FTP, cPanel File Manager, or WordPress Appearance > Theme Editor.
  3. Copy and paste the following code snippet at the end of functions.php:
/**
 * Adjust WooCommerce product price based on user role.
 */
add_filter( 'woocommerce_product_get_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'custom_role_based_price', 10, 2 );

function custom_role_based_price( $price, $product ) {
    if ( is_admin() ) {
        return $price; // Do not change price in admin area
    }

    if ( ! is_user_logged_in() ) {
        return $price; // Only modify price for logged-in users
    }

    $user = wp_get_current_user();
    $roles = (array) $user-roles;

    // Example role-based pricing adjustments
    if ( in_array( 'wholesale_customer', $roles ) ) {
        // 20% discount for wholesale customers
        $price = $price * 0.8;
    } elseif ( in_array( 'subscriber', $roles ) ) {
        // 10% discount for subscribers
        $price = $price * 0.9;
    }

    return $price;
}
  1. Save the file.
  2. Test your changes: Log in as a user with the wholesale_customer role and check product prices. Then test with a subscriber and a non-logged-in user to confirm pricing differences.

Common Pitfalls

  • Editing the wrong file: Always use a child theme or a custom plugin to avoid losing changes during theme updates.
  • Role names mismatch: Ensure the role slugs you use in the code exactly match the roles assigned to users.
  • Price caching: Some caching plugins or server-side caches may serve cached prices. Clear caches after applying changes.
  • Admin area price changes: The snippet avoids changing prices in the admin to prevent confusion during product editing.
  • Not handling variable products: This example works for simple products. Variable products require additional handling.

Works On

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.0 and above
WooCommerce Versions 3.0 and above

FAQ

Q: Can I add more roles or different discounts?
A: Yes. Simply add more elseif blocks inside the function checking for other roles and set your desired price adjustments.
Q: How do I create a custom user role like wholesale_customer?
A: Use a role management plugin like “User Role Editor” or add code to register a new role with add_role() in WordPress.
Q: Does this work with variable products?
A: This snippet targets simple products. Variable products require hooking into variation prices separately, which involves more complex code.
Q: Will this affect the price stored in the database?
No. This code only changes the price displayed on the front end dynamically. The original product price in the database remains unchanged.
Q: How can I prevent caching issues with role-based pricing?
Exclude pages with dynamic pricing from caching or use cache plugins that support dynamic content based on user roles.
…
WooCommerce How‑tos

WooCommerce: Exclude a category from the shop page

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Exclude a category from the shop page

WooCommerce: Exclude a Category from the Shop Page

If you want to hide a specific product category from the main WooCommerce shop page, this tutorial will show you how to quickly exclude that category using a simple code snippet. This is useful when you want to keep certain products available on your site but not visible on the primary shop listing.

Quick Fix

  1. Identify the slug of the product category you want to exclude.
  2. Add a custom function to your theme’s functions.php file or a site-specific plugin.
  3. Use the provided code snippet to modify the main WooCommerce query and exclude the category.
  4. Save changes and refresh the shop page to verify the category is hidden.

Why This Happens

By default, WooCommerce displays all published products on the shop page regardless of their categories. There is no built-in setting to exclude specific categories from appearing on the shop page. To customize this behavior, you need to modify the main product query using WordPress hooks to filter out products belonging to certain categories.

Requirements

  • Access to your WordPress theme files or ability to add custom code via a plugin.
  • Basic knowledge of editing PHP files.
  • WooCommerce installed and active.
  • Identify the category slug you want to exclude (found under Products > Categories).

Step-by-step

  1. Find the category slug:

    Go to WordPress Admin > Products > Categories. Locate the category you want to exclude and note its slug (e.g., hidden-category).

  2. Backup your site:

    Before editing any code, create a backup of your site or use a child theme to avoid losing changes after updates.

  3. Add the exclusion code:

    Edit your theme’s functions.php file or a custom plugin and add the following code snippet. Replace hidden-category with your actual category slug.

    function exclude_category_from_shop_page( $query ) {
        if ( ! is_admin() && $query-is_main_query() && is_shop() ) {
            $tax_query = (array) $query-get( 'tax_query' );
    
            $tax_query[] = array(
                'taxonomy' ='product_cat',
                'field'    ='slug',
                'terms'    =array( 'hidden-category' ), // Replace with your category slug
                'operator' ='NOT IN',
            );
    
            $query-set( 'tax_query', $tax_query );
        }
    }
    add_action( 'pre_get_posts', 'exclude_category_from_shop_page' );
    
  4. Save and test:

    Save the file and visit your WooCommerce shop page. The products from the specified category should no longer appear.

Common Pitfalls

  • Wrong category slug: Using the category name instead of the slug will not work. Always use the slug.
  • Code placed in the wrong file: Adding code to the wrong functions.php file (e.g., parent theme without a child theme) can cause issues on theme updates.
  • Cache issues: If you use caching plugins or server caching, clear caches to see the changes.
  • Conflicting plugins: Some plugins that modify queries may interfere with this code.
  • Not targeting the main query: The code only works if it modifies the main WooCommerce shop query.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, and others
  • WooCommerce versions 3.x and above
  • Any WordPress theme that supports WooCommerce

FAQ

Q: Can I exclude multiple categories at once?
A: Yes. Replace the 'terms' array with multiple slugs, like array('category-one', 'category-two').
Q: Will this hide the category from other pages like archives or widgets?
No. This code only affects the main WooCommerce shop page. You need additional customization to hide categories elsewhere.
Q: Can I exclude categories without editing code?
WooCommerce does not provide a built-in option to exclude categories from the shop page. You can use plugins that offer advanced product filtering or visibility controls if you prefer not to code.
Q: What if the code breaks my site?
Immediately remove the code via FTP or your hosting file manager. Always backup before making changes and test on staging environments.
Q: Does this affect SEO?
Excluding categories from the shop page does not remove them from your site or search engines. Ensure you manage category visibility thoughtfully to avoid duplicate content issues.
…
WooCommerce How‑tos

WooCommerce: Force login to purchase (hide price for guests)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Force login to purchase (hide price for guests)

WooCommerce: Force Login to Purchase (Hide Price for Guests)

If you want to restrict your WooCommerce store so that only logged-in users can see product prices and make purchases, this tutorial will show you how to do it quickly and effectively. By forcing users to log in before viewing prices or adding products to the cart, you can create a members-only shopping experience or better control customer access.

Quick Fix: Require Login to Purchase in WooCommerce

  1. Add a code snippet to your theme’s functions.php file or a site-specific plugin.
  2. Hide product prices and add-to-cart buttons for guests (non-logged-in users).
  3. Redirect guests to the login page when they try to access the cart or checkout.

Why This Happens

By default, WooCommerce displays product prices and allows purchases to all visitors, regardless of login status. However, some stores want to restrict this functionality to registered users only. WooCommerce does not have a built-in setting for this, so you need to customize it by adding code that hides prices and disables purchasing for guests.

This approach is common for wholesale stores, membership sites, or private catalogs where pricing and purchasing should be exclusive.

Requirements

  • WooCommerce installed and active on your WordPress site.
  • Access to your theme’s functions.php file or the ability to add custom PHP snippets via a plugin like Code Snippets.
  • Basic understanding of WordPress and WooCommerce templates.

Step-by-Step: Force Login to Purchase in WooCommerce

  1. Backup your site before making any code changes.
  2. Open your theme’s functions.php file or a site-specific plugin editor.
  3. Add the following code snippet:
<?php
// Hide prices and add to cart button for guests
function wc_hide_price_add_to_cart_for_guests() {
    if ( ! is_user_logged_in() ) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        add_filter( 'woocommerce_get_price_html', '__return_empty_string' );
        add_filter( 'woocommerce_cart_item_price', '__return_empty_string' );
        add_filter( 'woocommerce_cart_item_subtotal', '__return_empty_string' );
    }
}
add_action( 'wp', 'wc_hide_price_add_to_cart_for_guests' );

// Redirect guests to login page when trying to access cart or checkout
function wc_redirect_non_logged_users() {
    if ( ! is_user_logged_in() && ( is_cart() || is_checkout() ) ) {
        wp_safe_redirect( wp_login_url( wc_get_page_permalink( is_checkout() ? 'checkout' : 'cart' ) ) );
        exit;
    }
}
add_action( 'template_redirect', 'wc_redirect_non_logged_users' );
?>
  1. Save the file and test your site by logging out and visiting product pages, the cart, and checkout.

Common Pitfalls

  • Child Theme vs Parent Theme: Adding code to a parent theme’s functions.php can be overwritten on updates. Use a child theme or a site-specific plugin.
  • Cache Issues: If you use caching plugins or server caching, clear caches after adding the code to see changes immediately.
  • Login Redirect Loops: Ensure the login redirect URL is correct to avoid redirect loops.
  • Custom Themes or Plugins: Some themes or plugins might override WooCommerce hooks, so test thoroughly.

Works On

This solution works on all standard WooCommerce setups running on:

  • Apache and Nginx web servers
  • LiteSpeed servers
  • Hosting control panels like cPanel and Plesk
  • Any WordPress environment where you can add PHP code snippets

FAQ

Q: Can I customize the login redirect URL?
A: Yes, modify the wp_login_url() function parameter to any URL you want users to land on after login.
Q: Will this hide prices on all product types?
A: Yes, the snippet hides prices and add-to-cart buttons for all product types for guests.
Q: Can I show a custom message instead of hiding prices?
A: Yes, you can replace the price filters with a custom message by hooking into woocommerce_get_price_html and returning your message.
Q: Does this affect logged-in users?
No, logged-in users will see prices and can purchase products normally.
Q: Is there a plugin alternative?
Yes, some plugins offer membership or wholesale features that include login-to-purchase restrictions, but this code snippet is lightweight and free.
…
WooCommerce How‑tos

WooCommerce: Add a handling fee or surcharge

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Add a handling fee or surcharge

WooCommerce: Add a Handling Fee or Surcharge

Adding a handling fee or surcharge to your WooCommerce store can help cover extra costs such as packaging, payment processing, or special delivery requirements. This tutorial shows you how to woocommerce add handling fee quickly and effectively using custom code snippets, ensuring the fee appears transparently during checkout.

Quick Fix: Add a Handling Fee in WooCommerce

  1. Access your WordPress theme’s functions.php file or use a site-specific plugin.
  2. Copy and paste the provided PHP code snippet to add a fixed or percentage-based handling fee.
  3. Save changes and test the checkout to confirm the fee appears correctly.

Why This Happens

WooCommerce by default does not include a handling fee option. Many store owners need to add extra charges to cover costs beyond product prices and shipping. Since WooCommerce’s built-in fees are flexible but require manual input, adding a custom handling fee via code automates this process and ensures consistent application.

Requirements

  • WooCommerce installed and active on your WordPress site.
  • Access to your theme’s functions.php file or a custom plugin for adding PHP code.
  • Basic familiarity with editing WordPress files or using a code snippet plugin.

Step-by-Step: Adding a Handling Fee in WooCommerce

1. Backup Your Site

Before making any code changes, always backup your site to avoid accidental loss or downtime.

2. Open Your Theme’s functions.php File

Use FTP, cPanel File Manager, or the WordPress theme editor to open functions.php located in your active theme folder.

3. Add the Handling Fee Code Snippet

Paste the following code at the end of the functions.php file. This example adds a fixed handling fee of $5.00 to every order:

add_action( 'woocommerce_cart_calculate_fees', 'add_handling_fee' );
function add_handling_fee() {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $handling_fee = 5.00; // Fixed handling fee amount
    WC()-cart-add_fee( 'Handling Fee', $handling_fee, true, '' );
}

4. Save the File

Save your changes and upload the file back to the server if using FTP.

5. Test the Checkout

Add products to your cart and proceed to checkout. You should see the “Handling Fee” line item added to the order totals.

Optional: Percentage-Based Handling Fee

If you prefer a handling fee based on a percentage of the cart subtotal, use this code instead:

add_action( 'woocommerce_cart_calculate_fees', 'add_percentage_handling_fee' );
function add_percentage_handling_fee() {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 0.05; // 5% handling fee
    $cart_subtotal = WC()-cart-get_subtotal();
    $handling_fee = $cart_subtotal * $percentage;

    WC()-cart-add_fee( 'Handling Fee (5%)', $handling_fee, true, '' );
}

Common Pitfalls

  • Fee not showing: Ensure the code is placed in the active theme’s functions.php or a site-specific plugin, and WooCommerce is active.
  • Fee applied multiple times: The code checks for admin and AJAX contexts to prevent duplication. Avoid adding the snippet multiple times.
  • Tax settings: The third parameter in add_fee() controls if the fee is taxable. Set it to true or false depending on your tax rules.
  • Compatibility: Custom code may conflict with other plugins that modify cart fees. Test thoroughly.

Works On

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WordPress Versions WooCommerce compatible versions (4.0+ recommended)

FAQ

Q1: Can I add different handling fees based on payment method?

Yes. You can check the chosen payment method using WC()-session-get('chosen_payment_method') inside the fee function and conditionally add fees.

Q2: How do I make the handling fee tax-exempt?

Set the third parameter of add_fee() to false. For example: WC()-cart-add_fee( 'Handling Fee', $fee, false );

Q3: Can I add handling fees only for specific products or categories?

Yes. Use WC()-cart-get_cart() to loop through cart items and conditionally apply fees based on product IDs or categories.

Q4: Will this handling fee appear in order emails and invoices?

Yes. WooCommerce includes fees in order totals, so the handling fee will appear in emails, invoices, and admin order details.

Q5: Is there a plugin alternative to adding handling fees?

Yes. Plugins like “WooCommerce Advanced Fees” or “WooCommerce Extra Fees Plugin” offer GUI-based fee management without coding.…

WooCommerce How‑tos

WooCommerce: Disable shipping for virtual/downloadable products

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Disable shipping for virtual/downloadable products

WooCommerce: Disable Shipping for Virtual/Downloadable Products

If you run an online store using WooCommerce and sell virtual or downloadable products, you might want to disable shipping options for these products. Shipping is unnecessary for items that don’t require physical delivery, and disabling it improves the checkout experience and avoids confusion for customers. This tutorial shows you how to quickly disable shipping for virtual and downloadable products in WooCommerce with simple code snippets.

Quick Fix

  1. Add a custom function to your theme’s functions.php file or a site-specific plugin.
  2. Use WooCommerce hooks to conditionally remove shipping packages for virtual/downloadable products.
  3. Test your checkout to confirm shipping options do not appear for these products.

Why This Happens

By default, WooCommerce includes shipping calculations for all products unless they are explicitly marked as virtual or downloadable. Virtual products are intended to be intangible, such as services or memberships, while downloadable products are files customers can download after purchase. However, if a product is not properly configured or if shipping methods are not conditionally disabled, shipping options may still appear, causing confusion or unnecessary steps during checkout.

Requirements

  • WooCommerce installed and activated on your WordPress site.
  • Basic familiarity with editing theme files or creating a site-specific plugin.
  • Access to your WordPress admin dashboard or FTP/SFTP to add custom code.

Step-by-step: Disable Shipping for Virtual/Downloadable Products

  1. Backup your site. Before making any code changes, ensure you have a recent backup of your site files and database.
  2. Access your theme’s functions.php file. You can do this via WordPress admin under Appearance > Theme Editor or via FTP/SFTP.
  3. Add the following code snippet:
add_filter( 'woocommerce_cart_shipping_packages', 'disable_shipping_for_virtual_downloadable_products' );

function disable_shipping_for_virtual_downloadable_products( $packages ) {
    foreach ( $packages as $key => $package ) {
        $all_virtual = true;

        foreach ( $package['contents'] as $item ) {
            $product = $item['data'];

            if ( ! $product->is_virtual() && ! $product->is_downloadable() ) {
                $all_virtual = false;
                break;
            }
        }

        if ( $all_virtual ) {
            unset( $packages[ $key ] );
        }
    }

    return $packages;
}
  1. Save the file.
  2. Test your checkout. Add virtual or downloadable products to the cart and proceed to checkout. Shipping options should no longer appear. For physical products, shipping remains enabled.

Common Pitfalls

  • Not marking products as virtual or downloadable: The code depends on the product’s virtual or downloadable status. If these are not set correctly in the product edit screen, shipping will not be disabled.
  • Using caching plugins: Sometimes caching can prevent immediate reflection of changes. Clear your site and browser cache after adding code.
  • Theme or plugin conflicts: Some themes or shipping plugins may override WooCommerce shipping behavior. Test with default themes and disable conflicting plugins if needed.
  • Editing core WooCommerce files: Never edit WooCommerce core files directly; always use hooks and filters in your theme or custom plugin.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, and others
  • WooCommerce versions 3.0 and above
  • Compatible with most themes and child themes that follow WooCommerce standards

FAQ

Q: Can I disable shipping only for downloadable products but not virtual ones?
A: Yes. Modify the condition inside the loop to check only $product->is_downloadable() instead of both virtual and downloadable.
Q: What if I want to disable shipping only on certain shipping methods?
A: You can customize the code further by filtering shipping methods or using WooCommerce’s woocommerce_package_rates filter to selectively hide methods.
Q: Does this affect shipping calculations or just the display of shipping options?
A: This removes shipping packages entirely for virtual/downloadable products, so shipping is neither calculated nor displayed for those products.
Q: Can I add this code via a plugin instead of the theme’s functions.php?
A: Absolutely. Creating a site-specific plugin is recommended to keep customizations separate from theme updates.
Q: Will this work if I have mixed carts with both physical and virtual/downloadable products?
A: Yes. Shipping will only be disabled for packages containing exclusively virtual/downloadable products. Physical products will still trigger shipping options.
…
WooCommerce How‑tos

WooCommerce: Redirect after add to cart (to cart or checkout)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Redirect after add to cart (to cart or checkout)

WooCommerce: Redirect after Add to Cart (to Cart or Checkout)

By default, WooCommerce keeps customers on the product page after they add an item to their cart. Sometimes, you want to improve the shopping experience by redirecting users immediately to the cart or checkout page after adding a product. This tutorial explains how to implement a redirect after add to cart in WooCommerce quickly and reliably.

Quick Fix: Redirect After Add to Cart

  1. Choose whether to redirect to the cart page or the checkout page.
  2. Add a snippet of PHP code to your theme’s functions.php file or a site-specific plugin.
  3. Test the add-to-cart button to confirm the redirect works as expected.

Why This Happens

WooCommerce’s default behavior is designed to keep customers browsing products after adding an item to their cart. This can be good for discovery but sometimes disrupts the flow for customers ready to purchase. Redirecting after add to cart streamlines the checkout process by taking users directly to the cart or checkout page, reducing friction and potentially increasing conversions.

Requirements

  • WooCommerce plugin installed and active.
  • Access to your WordPress theme’s functions.php file or a site-specific plugin to add custom code.
  • Basic knowledge of editing PHP files in WordPress.

Step-by-step: Redirect After Add to Cart

  1. Backup your site. Always back up your site before editing theme files.
  2. Access your theme’s functions.php file. You can do this via Appearance > Theme Editor in WordPress admin or via FTP.
  3. Add the redirect code snippet. Copy and paste one of the following snippets depending on where you want to redirect users.

Code Snippet: Redirect to Cart Page

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_redirect_to_cart' );
function custom_redirect_to_cart() {
    return wc_get_cart_url();
}

Code Snippet: Redirect to Checkout Page

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_redirect_to_checkout' );
function custom_redirect_to_checkout() {
    return wc_get_checkout_url();
}
  1. Save the file. After adding the code, save your changes.
  2. Test the functionality. Visit a product page, add a product to the cart, and verify you are redirected to the cart or checkout page as intended.

Common Pitfalls

  • Theme or plugin conflicts: Some themes or plugins may override WooCommerce’s add to cart behavior, preventing the redirect from working.
  • AJAX add to cart enabled: If your theme uses AJAX for add to cart, the redirect filter may not trigger because the page does not reload.
  • Editing the wrong file: Ensure you add the code to your active theme’s functions.php or a site-specific plugin, not a parent theme if using a child theme.
  • Cache issues: Browser or server caching can interfere with testing changes. Clear caches after updating code.

Works on

Server/Environment Compatibility
Apache Fully compatible
Nginx Fully compatible
LiteSpeed Fully compatible
cPanel Fully compatible
Plesk Fully compatible

FAQ

Q: Why doesn’t the redirect work on my site?
A: If your theme uses AJAX add to cart, the redirect filter won’t trigger because the page doesn’t reload. You may need to disable AJAX add to cart or use JavaScript-based redirects.
Q: Can I redirect to a custom page after add to cart?
A: Yes. Replace wc_get_cart_url() or wc_get_checkout_url() with the URL of your custom page in the redirect function.
Q: Is it safe to add this code to my theme’s functions.php file?
A: Yes, but changes will be lost if you update the theme. Use a child theme or a site-specific plugin to keep changes persistent.
Q: How do I disable the redirect and go back to default behavior?
A: Remove or comment out the redirect filter code from your functions.php file or plugin.
Q: Will this affect variable or grouped products?
A: The redirect applies globally to all products added to the cart. However, AJAX add to cart on variable or grouped products may behave differently depending on your theme.
…
WooCommerce How‑tos

WooCommerce: Change “Add to cart” text per product type

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Change “Add to cart” text per product type

WooCommerce: Change “Add to cart” Text Per Product Type

If you want to customize the “Add to cart” button text in WooCommerce based on the product type, this guide will show you how to do it quickly and efficiently. Changing the button text per product type can improve user experience by providing context-specific calls to action, such as “Select options” for variable products or “Read more” for external products.

Quick Fix

  1. Identify the product types you want to customize (simple, variable, grouped, external).
  2. Add a custom function to your theme’s functions.php or a site-specific plugin.
  3. Use WooCommerce filters to change the button text based on product type.
  4. Test the changes on the frontend to confirm the new button text appears correctly.

Why This Happens

WooCommerce uses default button texts for different product types to guide customers appropriately. For example, variable products show “Select options” because customers need to choose variations before adding to cart. However, these defaults might not fit your store’s branding or messaging strategy. WooCommerce provides hooks and filters that allow developers to modify these texts without changing core files, ensuring updates won’t overwrite your customizations.

Requirements

  • WooCommerce installed and active on your WordPress site.
  • Access to your theme’s functions.php file or a custom plugin for adding PHP code.
  • Basic understanding of PHP and WordPress hooks.
  • Optional: Child theme to avoid losing changes on theme updates.

Step-by-step

  1. Backup your site: Always create a backup before editing theme files.
  2. Open your theme’s functions.php file: Use FTP, cPanel file manager, or the WordPress theme editor.
  3. Add the following code snippet:
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );

function custom_add_to_cart_text( $text, $product ) {
    if ( ! is_a( $product, 'WC_Product' ) ) {
        return $text;
    }

    switch ( $product->get_type() ) {
        case 'simple':
            $text = __( 'Buy Now', 'your-text-domain' );
            break;
        case 'variable':
            $text = __( 'Choose Options', 'your-text-domain' );
            break;
        case 'grouped':
            $text = __( 'View Products', 'your-text-domain' );
            break;
        case 'external':
            $text = __( 'Visit Website', 'your-text-domain' );
            break;
        default:
            $text = __( 'Add to cart', 'your-text-domain' );
            break;
    }

    return $text;
}
  1. Save the file and refresh your WooCommerce shop and product pages. You should see the new button texts based on product types.

Common Pitfalls

  • Editing the wrong file: Always use a child theme or a custom plugin to avoid losing changes after updates.
  • Missing product type check: Ensure the product object is valid before calling methods to avoid PHP errors.
  • Not using translation functions: Use __() or _e() for strings to support localization.
  • Cache issues: Clear your site and browser cache if changes don’t appear immediately.
  • Conflicts with other plugins: Some plugins may override button texts; test with plugins disabled if needed.

Works on

This method works on any WooCommerce installation regardless of your web server or control panel:

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, DirectAdmin
  • Hosting environments: Shared hosting, VPS, Dedicated servers
  • Compatible with most themes and WooCommerce versions (tested on WooCommerce 7.x and later)

FAQ

Q: Can I change the button text only on the shop/archive pages?
A: Yes. Use the woocommerce_product_add_to_cart_text filter for archive/shop pages and woocommerce_product_single_add_to_cart_text for single product pages. The example code above uses both.
Q: How do I translate the new button texts?
A: Wrap your strings with translation functions like __() and load your text domain properly in your theme or plugin. Use tools like Loco Translate to manage translations.
Q: What if I want different texts for specific products, not just product types?
A: You can extend the function to check product IDs or categories and return custom texts accordingly.
Q: Will this affect the functionality of the add to cart button?
No. This only changes the button text, not the underlying functionality.
Q: Can I use this code in a plugin instead of functions.php?
Yes. Creating a site-specific plugin is a best practice to keep your customizations independent of theme updates.
…
WooCommerce How‑tos

WooCommerce: Hide out‑of‑stock products from the catalog

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Hide out‑of‑stock products from the catalog

WooCommerce: Hide Out-of-Stock Products from the Catalog

If you run a WooCommerce store, displaying out-of-stock products can frustrate customers and clutter your catalog. The quick fix is to hide these unavailable products, improving user experience and focusing attention on what’s actually purchasable.

Quick Fix: Hide Out-of-Stock Products

  1. Go to your WordPress admin dashboard.
  2. Navigate to WooCommerce > Settings > Products > Inventory.
  3. Check the box labeled Hide out of stock items from the catalog.
  4. Save changes.

This built-in option immediately removes out-of-stock products from your shop and category pages without any coding.

Why This Happens

By default, WooCommerce shows all products regardless of stock status. This is to maintain SEO value and product visibility, but it can lead to poor user experience when customers find products they cannot buy. Hiding out-of-stock items ensures your catalog only features available products, reducing confusion and potentially increasing sales.

Step-by-Step: Hide Out-of-Stock Products with Code Snippets

If you want more control or the built-in option is insufficient (for example, to hide out-of-stock products only on specific pages), you can use custom code snippets.

  1. Backup your site before making code changes.
  2. Add the following snippet to your child theme’s functions.php file or a site-specific plugin:
function custom_hide_out_of_stock_products( $query ) {
    if ( ! is_admin() && $query-is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
        $meta_query = $query-get( 'meta_query' );
        if ( ! $meta_query ) {
            $meta_query = [];
        }
        $meta_query[] = [
            'key'     ='_stock_status',
            'value'   ='outofstock',
            'compare' ='!=',
        ];
        $query-set( 'meta_query', $meta_query );
    }
}
add_action( 'pre_get_posts', 'custom_hide_out_of_stock_products' );

This snippet modifies the main WooCommerce product queries on shop, category, and tag pages to exclude products marked as outofstock.

Common Pitfalls

  • Cache Issues: Changes may not appear immediately due to caching plugins or server cache. Clear all caches after applying settings or code.
  • Theme or Plugin Conflicts: Some themes or plugins override WooCommerce queries, which can prevent hiding out-of-stock products. Test with default themes or disable conflicting plugins.
  • Incorrect Hook Usage: Using the wrong hook or targeting the wrong query can cause the code not to work. Always use pre_get_posts for modifying product queries.
  • Stock Management Disabled: If stock management is off, WooCommerce won’t track stock status, so hiding out-of-stock products won’t work.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, and others
  • WooCommerce versions 3.0 and above
  • Compatible with most themes and plugins that respect WooCommerce query filters

FAQ

Q: Will hiding out-of-stock products affect SEO?
A: Hiding out-of-stock products removes them from catalog pages but does not delete them. They remain accessible via direct URLs unless you also change product visibility. This approach minimizes SEO impact but consider using 301 redirects if you remove products entirely.
Q: Can I hide out-of-stock products only on the shop page but show them in search results?
A: Yes. Modify the conditional in the code snippet to target only is_shop() and exclude other queries like search.
Q: What if I want to show a message instead of hiding out-of-stock products?
A: You can customize your theme’s product templates to display an “Out of stock” notice instead of hiding the product. This requires editing template files or using hooks.
Q: Does this method work with variable products?
A: Yes. WooCommerce treats variable products as in-stock if any variation is available. Out-of-stock variable products will be hidden if all variations are out of stock.
Q: How do I re-enable showing out-of-stock products?
A: Simply uncheck the “Hide out of stock items from the catalog” option in WooCommerce settings or remove the custom code snippet if used.
…
WooCommerce How‑tos

WooCommerce: Set a minimum order amount with a message

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Set a minimum order amount with a message

WooCommerce: Set a Minimum Order Amount with a Message

If you run a WooCommerce store, you might want to enforce a minimum order amount to ensure profitability or cover shipping costs. This tutorial shows you how to set a minimum order amount and display a clear message to customers when their cart total doesn’t meet the requirement.

Quick Fix

  1. Add a custom PHP snippet to your theme’s functions.php file or a site-specific plugin.
  2. Set your desired minimum order amount in the code.
  3. Customize the message shown to customers if the minimum is not met.
  4. Test the checkout process to confirm the restriction and message appear correctly.

Why This Happens

WooCommerce by default does not restrict customers from placing orders below a certain amount. This can lead to unprofitable sales or increased shipping costs that erode margins. Setting a minimum order amount helps maintain business rules by preventing checkout until the cart total reaches the threshold.

Without this restriction, customers might place orders that are too small to process efficiently or economically. The custom code hooks into WooCommerce’s validation process to enforce this rule and provide user feedback.

Requirements

  • WooCommerce installed and active on your WordPress site.
  • Access to your theme’s functions.php file or ability to add custom PHP code via a plugin.
  • Basic familiarity with editing WordPress theme files or using a code snippet plugin.

Step-by-step: Set a Minimum Order Amount in WooCommerce

  1. Backup your site: Always create a backup before editing theme files.
  2. Open your theme’s functions.php file: Use FTP, cPanel File Manager, or the WordPress theme editor.
  3. Add the following code snippet at the end of the file:
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );

function wc_minimum_order_amount() {
    // Set minimum order amount
    $minimum = 50; // Change this value to your desired minimum order amount

    if ( WC()-cart-total < $minimum ) {
        if( is_cart() ) {
            wc_print_notice( 
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to proceed to checkout.', 
                    wc_price( WC()-cart-total ), 
                    wc_price( $minimum )
                ), 'error' 
            );
        } else {
            wc_add_notice( 
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to proceed to checkout.', 
                    wc_price( WC()-cart-total ), 
                    wc_price( $minimum )
                ), 'error' 
            );
        }
    }
}
  1. Save the file.
  2. Test your store: Add products to your cart with a total below the minimum amount and try to proceed to checkout. You should see the error message preventing checkout.
  3. Adjust the $minimum value in the code snippet to your preferred minimum order amount.

Common Pitfalls

  • Editing the wrong file: Avoid editing WooCommerce plugin files directly. Use your child theme’s functions.php or a custom plugin.
  • Not backing up: Always back up before making changes to avoid site downtime.
  • Incorrect minimum value: Ensure the minimum amount is a numeric value and matches your currency format.
  • Cache issues: If changes don’t appear, clear your site and browser cache.
  • Theme conflicts: Some themes or plugins may override WooCommerce notices. Test with default themes if issues arise.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WooCommerce Versions WooCommerce 3.0 and above
WordPress Versions WordPress 5.0 and above

FAQ

Q: Can I set different minimum order amounts for different user roles?
A: Yes. You can modify the code to check the user role using current_user_can() or wp_get_current_user() and set different minimums accordingly.
Q: How do I change the minimum order amount currency?
A: The code uses wc_price() which automatically formats the amount based on your WooCommerce currency settings.
Q: Can I display the minimum order message on the cart page as well?
A: Yes. The provided code hooks into both the cart and checkout pages to show the message in both places.
Q: What if I want to set a minimum quantity instead of amount?
A: You would need to check WC()-cart-get_cart_contents_count() instead of WC()-cart-total and adjust the logic accordingly.
Q: Will this prevent orders below the minimum amount from being placed?
A: Yes. The code adds an error notice and prevents checkout submission until the minimum order amount is met.
…
WooCommerce How‑tos

WooCommerce: Remove checkout fields safely (no plugin)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Remove checkout fields safely (no plugin)

WooCommerce: Remove Checkout Fields Safely (No Plugin)

When customizing your WooCommerce checkout page, you might want to remove unnecessary fields to simplify the user experience or tailor the form to your business needs. However, removing checkout fields incorrectly can cause errors or affect order processing. This guide shows you how to safely remove WooCommerce checkout fields without using a plugin by adding custom code to your theme or child theme.

Quick Fix: Remove WooCommerce Checkout Fields

  1. Identify the checkout fields you want to remove.
  2. Add a custom PHP function to your theme’s functions.php file or a site-specific plugin.
  3. Use the woocommerce_checkout_fields filter to unset the fields you want to remove.
  4. Test the checkout page to ensure the fields are removed and the checkout works correctly.

Why This Happens

WooCommerce checkout fields are defined in an array that includes billing, shipping, and additional fields. By default, WooCommerce requires certain fields for processing orders, but many fields are optional or customizable. Removing fields directly from the template files or via plugins without using the proper hooks can cause validation errors or break the checkout process. Using the woocommerce_checkout_fields filter allows you to safely modify the checkout fields array before it is rendered and validated.

Requirements

  • Access to your WordPress site’s theme files (preferably a child theme).
  • Basic knowledge of PHP and WordPress theme editing.
  • WooCommerce plugin installed and active.
  • FTP or hosting file manager access to restore files if needed.

Step-by-Step: Remove Checkout Fields in WooCommerce

  1. Backup your site. Always create a backup before editing theme files.
  2. Access your theme’s functions.php file. You can do this via Appearance > Theme Editor in WordPress admin or through FTP/cPanel file manager.
  3. Add the following code snippet to remove unwanted checkout fields. Customize the fields you want to remove by unsetting them from the array.
function custom_remove_woocommerce_checkout_fields( $fields ) {
    // Remove billing phone field
    unset( $fields['billing']['billing_phone'] );

    // Remove billing company field
    unset( $fields['billing']['billing_company'] );

    // Remove shipping address 2
    unset( $fields['shipping']['shipping_address_2'] );

    // Remove order comments
    unset( $fields['order']['order_comments'] );

    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'custom_remove_woocommerce_checkout_fields' );
  1. Save the file and test your checkout page. Visit the checkout page and verify the specified fields are no longer visible.
  2. Check order processing. Place a test order to ensure no validation errors occur and the order completes successfully.

Common Pitfalls

  • Removing required fields: Some fields like billing email or billing address are required for order processing. Removing them can cause checkout validation errors.
  • Editing parent theme files: Avoid editing the parent theme directly; use a child theme to prevent losing changes during updates.
  • Cache issues: Clear your site and browser cache after making changes to see the updated checkout form.
  • Plugin conflicts: Other plugins may add or modify checkout fields; test changes with plugins disabled if issues arise.

Works On

This method works on sites running WooCommerce on:

  • Apache or Nginx web servers
  • LiteSpeed servers
  • Hosting panels like cPanel and Plesk
  • Any WordPress theme that supports WooCommerce (preferably child themes)

FAQ

Q: Can I remove all checkout fields using this method?
A: You can remove most optional fields, but some fields are required by WooCommerce and should not be removed to avoid checkout errors.
Q: Will this code be overwritten when WooCommerce updates?
No. Since the code is added to your theme’s functions.php or a custom plugin, WooCommerce updates will not overwrite it.
Q: How do I find the exact field names to remove?
You can inspect the checkout form HTML or refer to WooCommerce documentation. Common field keys include billing_phone, billing_company, shipping_address_2, and order_comments.
Q: Can I add fields back later?
Yes. To add fields back, simply remove the unset() line for that field or add custom fields using the same woocommerce_checkout_fields filter.
Q: Is it better to use a plugin for this?
While plugins offer UI-based field management, using code is more lightweight and gives you full control without adding extra plugins.
…
WooCommerce How‑tos

Posts pagination

1 2 Next

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme

    Also by the maker of MySurveyReviews.com