I'be seen a few videos where they added a rating number field. I was hoping to add this field to a comment post type but thats not available.
Should I create a reviews post type and add a rating field to is? Then relate reviews to my member profile CPT? If so, how do we display averages to the user?
That feature would not be available even if the first option was available. You will need custom development for that to create a PHP code snippet to show such a feature.
This is outside of our support scope, but I will try to give you the starting point which is checking all the post entries and get the rating field number and calculate the average:
function calculate_average_rating() {
// Arguments for WP_Query
$args = array(
'post_type' => 'rating', // Custom post type name
'posts_per_page' => -1, // Retrieve all posts
'post_status' => 'publish', // Only published posts
);
// Custom query
$query = new WP_Query($args);
// Initialize variables
$total_rating = 0;
$total_reviews = 0;
// Loop through posts
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Get custom field value (assuming the custom field is named 'review_number')
$rating = get_post_meta(get_the_ID(), 'review_number', true);
// Add rating to total if it's a valid number
if (is_numeric($rating)) {
$total_rating += $rating;
$total_reviews++;
}
}
wp_reset_postdata(); // Reset post data
}
// Calculate average
if ($total_reviews > 0) {
$average_rating = $total_rating / $total_reviews;
return 'Average Rating: ' . round($average_rating, 2);
} else {
return 'No reviews found.';
}
}
// Register shortcode
add_shortcode('average_rating', 'calculate_average_rating');
Add [average_rating] where you want to display the average rating.
Explanation:
WP_Query: This is used to retrieve all posts of the custom post type "rating".
get_post_meta: This function gets the value of the custom field review_number for each post.
Calculations: The code sums up all valid ratings and calculates the average.
Shortcode registration: The add_shortcode function registers the shortcode [average_rating].
Important Note: The code above is not a final solution, it is just and idea of how to create an average and it needs further development.
If you are not familiar with PHP programming you can consider hiring a developer:
Yes - you may try to search for the rating plugin and try to play with it to know what could be the best option for you for the rating/review functionality.