wp_star_rating() - Adding a 5 star rating system to theme
-
29-09-2020 - |
Question
My goal is to add a 5 star rating system to my theme. I read that there's a function wp_star_rating
in wp-admin/includes/template.php
on line 2121, that I've been trying to use for the ratings. I am using WP 4.0. Just using wp_star_rating()
in my theme's content.php alone returns:
Fatal error: Call to undefined function wp_star_rating() in [LOCALHOST URI]\content.php on line 12
In my theme's content.php, I'm trying to use wp_star_rating(). If I redeclare wp_star_rating() in my theme's functions.php the content works but when I go to my admin panel I get the error (obviously) that I can't redeclare the function.
Besides redeclaring the function I also tried (in my theme's functions.php):
if( !function_exists('wp_star_rating') ){
require admin_url() . 'includes/template.php';
}
I'm aware this doesn't work because it doesn't like the full url.
The only thing I tried that partially worked (displayed on front end but threw error on backend):
include '/wp-admin/includes/template.php';
So the question is: How can I use wp_star_rating() in my theme's content.php file? Or how do I include it in my theme?
I already have everything else enqueI'm sure there's a simple solution I'm missing but after a few days of searching I have not found much help. I really can't afford spending all of my time on this issue.
Solution
Instead of redefining wp_star_rating()
for the front end, you should be able to just use the built-in function.
From the Codex page for wp_star_rating()
:
In order to use this function on the front end, your template must include the
wp-admin/includes/template.php
file and enqueue the appropriate dashicons CSS font information.
(emphasis mine)
A code sample is also provided in the Notes section of the Codex page.
Edit
If you're getting Fatal error: Call to undefined function wp_star_rating()
messages, that means that you have not included wp-admin/includes/template.php
in your file. Try adding this snippet somewhere prior to your call to wp_star_rating()
:
require_once( ABSPATH . 'wp-admin/includes/template.php' );
That should allow you to use wp_star_rating()
in your front-end code.