The website I am working on requires you to be logged in to see prices and I've been using a plugin to do this. However, I was just thrown a curve ball and told that one specific category on the website must have prices shown all the time, regardless if the user is logged in or not.
It looks like the plugin uses
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
and
remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
to remove the prices. And this is how I am trying to re-add the prices in for products in the specific category:
function make_surplus_price_always_visible(){
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;
if ( in_array( 'surplus-allison-parts', $categories ) && !is_user_logged_in()) {
?>
<script>
alert('product in surplus');
</script>
<?php
//add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
}
}
add_action('woocommerce_after_shop_loop_item_title', 'make_surplus_price_always_visible', 50);
but it doesn't add the prices back. The jQuery alert is working so it's not a matter of meeting the "if" statement requirements.
How can I go about adding back the product prices for a specific category?
Updated: Here is the correct way to make it work:
has_term()
Wordpress function for the product category.The code:
add_action('woocommerce_after_shop_loop_item_title', 'shop_loop_make_surplus_price_always_visible', 8 );
function shop_loop_make_surplus_price_always_visible(){
global $post;
// Set here your product categories (Names, slugs or IDs) in this array
$categories = array( 'surplus-allison-parts' );
if ( has_term( $categories, 'product_cat', $post->ID ) && ! is_user_logged_in()) {
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
}
}
And:
add_action('woocommerce_single_product_summary', 'single_product_make_surplus_price_always_visible', 8 );
function single_product_make_surplus_price_always_visible(){
global $post;
// Set here your product categories (Names, slugs or IDs) in this array
$categories = array( 'surplus-allison-parts' );
if ( has_term( $categories, 'product_cat', $post->ID ) && ! is_user_logged_in()) {
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works