Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Created May 24, 2019 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielbachhuber/f4c4c27dd839846649a7c948deb2850f to your computer and use it in GitHub Desktop.
Save danielbachhuber/f4c4c27dd839846649a7c948deb2850f to your computer and use it in GitHub Desktop.
<?php
/**
* Adds the Tasty Recipes ratings to the top of the post.
*
* @param string $content Existing post content.
* @return string
*/
add_filter( 'the_content', function( $content ) {
if ( ! class_exists( 'Tasty_Recipes' ) ) {
return $content;
}
// Get all of the recipes that might be in the post.
$recipe_ids = Tasty_Recipes::get_recipe_ids_from_content( $content );
if ( ! empty( $recipe_ids ) ) {
// Get the first recipe ID in the post and fetch its object.
$recipe_id = array_shift( $recipe_ids );
$recipe = Tasty_Recipes\Objects\Recipe::get_by_id( $recipe_id );
if ( $recipe ) {
// Fetch all total reviews, but only process if there's more than zero reviews.
$total_reviews = $recipe->get_total_reviews();
if ( $total_reviews ) {
// Build the label and icon markup.
$average_rating = round( (float) $recipe->get_average_rating(), 1 );
$recipe_rating_label = '<span class="rating-label">';
$recipe_rating_label .= sprintf(
// translators: Ratings from number of reviews.
__( '%1$s from %2$s reviews', 'tasty-recipes' ),
'<span class="average">' . $average_rating . '</span>',
'<span class="count">' . (int) $total_reviews . '</span>'
);
$recipe_rating_label .= '</span>';
$recipe_rating_icons = Tasty_Recipes\Ratings::get_rendered_rating( $average_rating );
// Prepend the ratings markup to the post content.
$content = '<p>' . $recipe_rating_icons . '</p><p>' . $recipe_rating_label . '</p>' . PHP_EOL . $content;
}
}
}
return $content;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment