Created
August 29, 2017 23:15
-
-
Save arsalan13nov/bb7a8ff2c508ef547312671bd4dff5db to your computer and use it in GitHub Desktop.
Snippet to hide price on WooCommerce products in selected category.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**** Custom Code to hide product prices based on the associatin with specific categories. ****/ | |
/**** Place the following code at the bottom of theme's functions.php file. ****/ | |
/** | |
* Remove price on product detail page | |
* | |
* @param none | |
* @return none | |
*/ | |
function remove_prices_based_on_category() { | |
// If its a product detail page. | |
if ( is_product() ) { | |
remove_product_price( get_the_ID() ); | |
} | |
} | |
add_action( 'wp', 'remove_prices_based_on_category' ); | |
/** | |
* To remove price of a product by product id. | |
* | |
* @param $product_id | |
* @return none | |
*/ | |
function remove_product_price( $product_id ) { | |
$product_id = get_the_ID(); | |
$hidden_price_category_ids = array( '27419','27421' ); // Add Product Category IDs for which the product price should be hidden. | |
$product_cat_ids = get_the_terms( $product_id, 'product_cat' ); // Getting all categories for this product. | |
$cat_ids = wp_list_pluck( $product_cat_ids, 'term_id' ); // Getting all category ids for this product. | |
$result = array_intersect( $hidden_price_category_ids, $cat_ids ); // Will match hidden price categories with product categories and the cat id in the array. | |
// If a hidden pice category is found | |
if( !empty($result) ) { | |
add_filter( 'woocommerce_get_price_html', 'return_custom_price', 10, 2 ); | |
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); | |
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' ); | |
} else { | |
remove_filter( 'woocommerce_get_price_html', 'return_custom_price', 10, 2 ); | |
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); | |
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' ); | |
} | |
} | |
add_action( 'woocommerce_before_shop_loop_item', 'remove_product_price', 5, 1 ); // for each product on product listing page/shop page. | |
/** | |
* To remove price of a product by product id. | |
* | |
* @param $price price html | |
* @return string price html | |
*/ | |
function return_custom_price( $price, $instance ) { | |
$price = '<span style="color:red; font-size:12px;">Call our office <strong>516.695.3110</strong> for prices.</span>'; | |
return $price; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment