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.
- Copy the code below into your WordPress theme's
functions.php
file or a custom plugin. - Adjust the
$excluded_categories
array if needed to match your specific category slugs.
// 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;
}
- 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.