Skip to content

Instantly share code, notes, and snippets.

@phirebase
Created January 27, 2025 14:37
Show Gist options
  • Save phirebase/6b1270fdfdf15185786c93ed1dd16882 to your computer and use it in GitHub Desktop.
Save phirebase/6b1270fdfdf15185786c93ed1dd16882 to your computer and use it in GitHub Desktop.

Exclude Unit Price for Specific WooCommerce Products

This code snippet overrides the WooCommerce Price Per Unit plugin to exclude unit price for products in the your-category category. It dynamically removes the unit price display for specific products based on their category.

Usage

  1. Copy the code below into your WordPress theme's functions.php file or a custom plugin.
  2. Adjust the $excluded_categories array if needed to match your specific category slugs.

Code

// Exclude unit price for products in the "your-category" category

add_filter('woocommerce_get_price_html', 'exclude_unit_price_for_gift_cards', 9999, 2);

function exclude_unit_price_for_gift_cards($price_html, $product) {
    // Ensure the product is a WC_Product object
    if (!is_a($product, 'WC_Product')) {
        $product = wc_get_product($product);
    }

    // Verify the product exists
    if (!$product) {
        return $price_html;
    }

    // Slug of the category to exclude
    $excluded_categories = array('your-category'); // Replace with your category slug

    // Get the product's categories
    $product_categories = wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'slugs'));

    // Check if the product matches the excluded categories
    if (array_intersect($excluded_categories, $product_categories)) {
        // Return the regular price without any unit price
        return wc_price($product->get_price());
    }

    // Return the original price for other products
    return $price_html;
}

Notes

  • The filter priority is set to 9999 to ensure this logic overrides any other modifications applied by the Woo Price Per Unit plugin.
  • Adjust the excluded_categories array as needed to exclude additional categories.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment