Works as expected – here’s a custom shortcode
-
Here’s a custom function to display the page rating by itself anywhere on the page:
function custom_wpcr3_reviews_info_shortcode($atts) { // Shortcode attributes $atts = shortcode_atts( array( 'post_id' => null, // Default to null, so it can be used for the current post/page ), $atts, 'custom_wpcr3_reviews_info' ); // Query to retrieve posts of type 'wpcr3_review' $reviews_query = new WP_Query(array( 'post_type' => 'wpcr3_review', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'wpcr3_review_post', 'value' => $atts['post_id'], ), ), )); // Initialize variables $total_reviews = $average_rating = 0; // Loop through each review post while ($reviews_query->have_posts()) { $reviews_query->the_post(); // Get post ID and corresponding review post ID $review_post_id = get_the_ID(); // Get the rating for the current review post $rating = get_post_meta($review_post_id, 'wpcr3_review_rating', true); // Increment total reviews and add rating to the total $total_reviews++; $average_rating += intval($rating); } // Reset the post data wp_reset_postdata(); // Calculate average rating in stars $average_rating = $total_reviews > 0 ? round($average_rating / $total_reviews) : 0; // Output HTML for displaying reviews info $output = '<div class="custom-wpcr3-reviews-info">'; $output .= '<p><a href="#reviews"><strong>Average Rating:</strong><span style="color:#ff6900;text-shadow: 1px 1px #999;"> ' . str_repeat('★', $average_rating) . ' (' . $total_reviews . ' reviews)</span></a></p>'; $output .= '</div>'; return $output; } // Register the custom shortcode add_shortcode('custom_wpcr3_reviews_info', 'custom_wpcr3_reviews_info_shortcode');
use the shortcode like this: [custom_wpcr3_reviews_info post_id=37]
- The topic ‘Works as expected – here’s a custom shortcode’ is closed to new replies.