I want to hide the stars rating below the title on the products where the reviews are empty. I want to hide only the stars without the ability to leave a new review. I found a similar solution for hiding a different element and tried to adopt it.
I added this using a snippets plugin to add a class "hide-empty-stars" in body_class when the reviews are empty.
function check_for_empty_stars( $classes ) {
global $product;
$id = $product->get_id();
$args = array ('post_type' => 'product', 'post_id' => $id);
$comments = get_comments( $args );
if(empty($comments)) {
$classes[] = 'hide-empty-stars';
}
return $classes;
}
add_filter( 'body_class', 'check_for_empty_stars' );
Then I hide the star-rating class using css
body.hide-empty-stars .star-rating{
display: none;
}
It works but after a while I get a critical error and the log says that
mod_fcgid: stderr: PHP Fatal error: Uncaught Error: Call to a member function get_id() on null in /var/www/vhosts/my-domain.gr/httpdocs/wp-content/plugins/code-snippets/php/snippet-ops.php(505) : eval()'d code:3
What could cause this? Is there anything wrong in my code?
CodePudding user response:
It occurs when you are not on the product page. The body_class
runs on every page but some pages do not have post ID - for example category pages. Your snippet should run only if there is an post ID defined. Let's say you are looking at page presenting some category - there is not $product
variable but you try to call get_id();
on $product
so you get the error.
Maybe try to wrap it in if statement?
function check_for_empty_stars( $classes ) {
global $product;
if (!is_null($product)) {
$id = $product->get_id();
$args = array ('post_type' => 'product', 'post_id' => $id);
$comments = get_comments( $args );
if(empty($comments)) {
$classes[] = 'hide-empty-stars';
}
}
return $classes;
}
add_filter( 'body_class', 'check_for_empty_stars' );
Or just look for filter which will run only on product pages. Also - you don't need any plugin like code-snippets. You can just place this code in the functions.php of your child-theme. Read about child-themes, these are good if you want to modify the theme and you will not lost your changes after updates. https://developer.wordpress.org/themes/advanced-topics/child-themes/