Home / Disable / Leave Tasty recipe ratings with WP-PostRatings
Duplicate Snippet

Embed Snippet on Your Site

Leave Tasty recipe ratings with WP-PostRatings

The Tasty Recipes rating system works with the default WordPress comment form. However, if you use a different comment system, such as a theme-specific one or a plugin like Discus, you will need to use a separate rating system.

<10
Code Preview
php
<?php
// Disable standard ratings UI
add_filter( 'tasty_recipes_enable_ratings', '__return_false' );
/**
 * Filter template variables to render WP-PostRatings UI
 * within the recipe card.
 *
 * @param array $template_vars Variables to be passed to the template.
 * @param object $recipe       Recipe object.
 * @return array
 */
add_filter( 'tasty_recipes_recipe_template_vars', function( $template_vars, $recipe ){
	if ( function_exists( 'the_ratings' ) ) {
		// Render the WP-PostRatings UI within the recipe card
		$template_vars['recipe_rating_icons'] = the_ratings( 'span', $recipe->get_id(), false );
		// Hide from display, but keep for microdata
		$template_vars['recipe_rating_label'] = str_replace( '<span ', '<span style="display:none;" ', $template_vars['recipe_rating_label'] );
	}
	return $template_vars;
}, 10, 2 );
/**
 * When a rating is saved for a recipe, put the data in
 * the place Tasty Recipe expects.
 *
 * @param integer $user_id User saving the rating.
 * @param integer $post_id Post ID for the rating (should be a recipe post).
 */
add_action( 'rate_post', function( $user_id, $post_id ){
	if ( 'tasty_recipe' !== get_post_type( $post_id ) ) {
		return;
	}
	$average_rating = get_post_meta( $post_id, 'ratings_average', true );
	$total_reviews = get_post_meta( $post_id, 'ratings_users', true );
	update_post_meta( $post_id, 'average_rating', $average_rating );
	update_post_meta( $post_id, 'total_reviews', $total_reviews );
}, 10, 2 );

Comments

Add a Comment