Add Star Ratings to WordPress on the Backend Using Custom Fields
Tags: wordpress
Published: 2021-03-23 03:24:56

<!-- wp:paragraph -->
<p>Star rating must be very familiar to Internet users: users are able to rate or write reviews of a product they buy on an eCommerce website. Moreover, these star reviews also appear on product review sites. Reviewers on those sites will score and rate products based on their own experiences and reviews, such as this <a href="https://freewpthemes.reviews/">theme review page</a>.</p>
<p><!--more--></p>
<p>To help the website owner to add star ratings on their review website, you can use <a href="https://metabox.io/series/custom-field">custom fields</a> and create a plugin yourself to add star ratings. That is the topic of today's tutorial.</p>
<p>First of all, you need to download and install <a href="https://metabox.io/">Meta Box</a> plugin - a framework for creating custom fields. This Meta Box core plugin is free at <a href="https://wordpress.org/plugins/meta-box">wordpress.org</a>. After downloading, start working on it.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Step 1: Create a New Plugin to Add Star Ratings</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To add star ratings with custom fields, you should create a new plugin. In this way, it’s more convenient each time you reuse this feature.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I name this plugin <strong>MB Rating Field</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First, we start building this new plugin with the directory structure like so:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>wp-content / plugins / mb-rating-field
  - css
  - admin.css
  - frontend.css
rating.php
mb-rating-field.php
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In it, the <code>mb-rating-field.php</code> file has the following content:</p>
<pre> ? php<br />/ **<br /> * Plugin Name: MB Star Rating<br /> * URI plugin: https://metabox.io<br /> * Description: Add a new star rating field type for Meta Box<br /> * Version: 1.0<br /> * Author: MetaBox.io<br /> * Author URI: https://metabox.io<br /> * License: GPLv2<br /> * /</pre>
<p>Then, activate this plugin in the list of installed plugins in the Dashboard.</p>
<p><img class="aligncenter" src="https://i.imgur.com/Rqaeerr.png" alt="Install the new plugin to add star ratings to WordPress on the backend" width="1349" height="657" /></p>
<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>Next, we are going to start building the function to create custom fields for the star rating feature of this plugin, following these steps:</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Step 2: Create a Field Type to Add Star Ratings</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In this step, we will create a new field type called rating to add star ratings.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>First, create a class named <code>RWMB_Rating_Field</code> for this rating field. Usually, if you want to create a certain type of field, you should create a class with the syntax <code>RWMB _ {$ field_type} _Field</code>. You can see more details in <a href="https://docs.metabox.io/custom-field-type/">this guide</a> of Meta Box.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>if (class_exists ('RWMB_Field')) {
    class RWMB_Rating_Field extends RWMB_Field {}
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, save this class to a PHP file (for example, I save it in the <code>rating.php</code> file), then put this file in the plugin <code>mb-rating-field.php</code> file created in Step 1.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>add_action ('init', 'prefix_load_rating_type');
function prefix_load_rating_type () {
    require __DIR__. '/rating.php';
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Step 3: Create Options to Add Star Rating for the Rating Field</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Once you have the rating field, you need to create options that allow website owners to score stars (from 0.5 to 5 stars).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This rating class will inherit all the methods of the <code>RWMB_Field class</code>. In this rating field, we must specify the content of the <strong>html</strong> method to output the HTML in the backend.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Do it by adding the following code to the <code>rating.php</code> file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>public static function html ($ meta, $ field) {
    return sprintf (
        '&lt;fieldset class = "rwmb-rating" id = "% 1 $ s"&gt;
        &lt;input type = "radio" '. checked ($ meta, 5, false). 'id = "% 1 $ s_star5" name = "% 2 $ s" value = "5" /&gt; &lt;label class = "full" for = "% 1 $ s_star5" title = "5 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 4.5, false). 'id = "% 1 $ s_star4half" name = "% 2 $ s" value = "4.5" /&gt; &lt;label class = "half" for = "% 1 $ s_star4half" title = "4.5 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 4, false). 'id = "% 1 $ s_star4" name = "% 2 $ s" value = "4" /&gt; &lt;label class = "full" for = "% 1 $ s_star4" title = "4 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 3.5, false). 'id = "% 1 $ s_star3half" name = "% 2 $ s" value = "3.5" /&gt; &lt;label class = "half" for = "% 1 $ s_star3half" title = "3.5 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 3, false). 'id = "% 1 $ s_star3" name = "% 2 $ s" value = "3" /&gt; &lt;label class = "full" for = "% 1 $ s_star3" title = "3 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 2.5, false). 'id = "% 1 $ s_star2half" name = "% 2 $ s" value = "2.5" /&gt; &lt;label class = "half" for = "% 1 $ s_star2half" title = "2.5 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 2, false). 'id = "% 1 $ s_star2" name = "% 2 $ s" value = "2" /&gt; &lt;label class = "full" for = "% 1 $ s_star2" title = "2 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 1.5, false). 'id = "% 1 $ s_star1half" name = "% 2 $ s" value = "1.5" /&gt; &lt;label class = "half" for = "% 1 $ s_star1half" title = "1.5 stars"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 1, false). 'id = "% 1 $ s_star1" name = "% 2 $ s" value = "1" /&gt; &lt;label class = "full" for = "% 1 $ s_star1" title = "1 star"&gt; &lt;/label&gt;
        &lt;input type = "radio" '. checked ($ meta, 0.5, false). 'id = "% 1 $ s_starhalf" name = "% 2 $ s" value = "0.5" /&gt; &lt;label class = "half" for = "% 1 $ s_starhalf" title = "0.5 stars"&gt; &lt;/label&gt;
        &lt;/fieldset&gt; ',
        $ field ['field_name'],
        $ field ['id'],
        $ meta
    );
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here, we use the "radio" field type to give the user a 0.5 to 5 band score to rate.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next, we need to style a little to show the above radio options as stars (currently they are only visible as small circles).</p>
<p><img class="aligncenter" src="https://i.imgur.com/H4i8UpX.png" alt="Create Options to Add Star Rating for the Rating Field" width="1478" height="163" /></p>
<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>Just add this code to the <code>css/admin.css</code> file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>.rwmb-rating {
    border: none;
    float: left;
}
.rwmb-rating &gt; input { display: none; }
.rwmb-rating &gt; label:before {
    margin: 5px;
    font-size: 1.25em;
    font-family: FontAwesome;
    display: inline-block;
    content: "\f005";
}
 
.rwmb-rating &gt; .half:before {
    content: "\f089";
    position: absolute;
}
.rwmb-rating &gt; label {
    color: #ddd;
    float: right;
}
/***** CSS Magic to Highlight Stars on Hover *****/
 
.rwmb-rating &gt; input:checked ~ label, /* show gold star when clicked */
.rwmb-rating:not(:checked) &gt; label:hover, /* hover current star */
.rwmb-rating:not(:checked) &gt; label:hover ~ label { color: #FFD700;  } /* hover previous stars in list */
.rwmb-rating &gt; input:checked + label:hover, 
.rwmb-rating &gt; input:checked ~ label:hover,
.rwmb-rating &gt; label:hover ~ input:checked ~ label, .rwmb-rating &gt; input:checked ~ label:hover ~ label { color: #FFED85;  }
.rwmb-rating input[type=radio]:checked+label:before {
    color: unset;
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To get the style in admin, we use the function <code>admin_enqueue_scripts ()</code> to enqueue. Please enqueue in the <code>rating.php</code> file as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>public static function admin_enqueue_scripts() {
wp_enqueue_style( 'rwmb-rating', plugin_dir_url( __FILE__ ) . '/css/admin.css', array(), '1.0.0' );
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The <code>rating.php</code> file has this content: <a href="https://github.com/elightup/mb-rating-field">https://github.com/elightup/mb-rating-field</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Step 4: Create Custom Fields to Add Star Ratings with MB Star Rating Plugin</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now, we can create custom fields with rating field type using the newly created MB Star Rating plugin!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You just need to put the following code in the <code>functions.php</code> file of your theme or <a href="https://gretathemes.com/what-is-child-theme/" rel="follow">child theme</a>, note that <code>'type' =&gt; ‘rating'</code> is set as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>&lt;?php
add_filter( 'rwmb_meta_boxes', 'your_prefix_register_meta_boxes' );
function your_prefix_register_meta_boxes( $meta_boxes ) {
    $prefix = '';
    $meta_boxes[] = [
        'title'      =&gt; esc_html__( 'Project Field', 'text-domain' ),
        'id'         =&gt; 'project-field',
        'post_types' =&gt; ['post'],
        'context'    =&gt; 'normal',
        'priority'   =&gt; 'high',
        'fields'     =&gt; [
            [
                'id'   =&gt; $prefix . 'name',
                'type' =&gt; 'text',
                'name' =&gt; esc_html__( 'Name', 'text-domain' ),
            ],
            [
                'id'   =&gt; $prefix . 'rating',
                'type' =&gt; 'rating',
                'name' =&gt; esc_html__( 'Rating', 'text-domain' ),
            ],
        ],
    ];
    return $meta_boxes;
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, when you go to the post / page editor, you will see the created custom field display as follows:</p>
<p><img class="aligncenter" src="https://i.imgur.com/Uw9soDm.png" alt="The custom fields to add star ratings created by MB Star Rating plugin" width="1482" height="174" /></p>
<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>And just enter the name and rate:</p>
<p><img class="aligncenter" src="https://i.imgur.com/EuREdEW.png" alt="Enter the name and rate by the star rating field" width="1444" height="171" /></p>
<!-- /wp:embed -->

<!-- wp:heading -->
<h2>Step 5: Display The Star Ratings on The Frontend</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>So, we have created a custom field to add star ratings to a post / page on the backend. To display it on the frontend for readers to view, you can use the WordPress <code>wp_star_rating ()</code> function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the <code>rating.php</code> file, you use the <code>format_single_value ()</code> method by adding this code:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>public static function format_single_value( $field, $value, $args, $post_id ) {
	wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'frontend', plugin_dir_url(__FILE__) . '/css/frontend.css' );
 
require_once ABSPATH . 'wp-admin/includes/template.php';
$starrating = rwmb_get_value( $field['id'] );
       $args = array(
       	'rating' =&gt; $starrating,
             'type' =&gt; 'rating',
       );
       wp_star_rating( $args );
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The above code will output the following HTML in the frontend:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>&lt;div class = "star-rating" title = "" Number of stars obtained "rating"&gt;
     &lt;div class = "star star-full"&gt; &lt;/div&gt;
     &lt;div class = "star star-full"&gt; &lt;/div&gt;
     &lt;div class = "star star-full"&gt; &lt;/div&gt;
     &lt;div class = "star star-half"&gt; &lt;/div&gt;
     &lt;div class = "star star-empty"&gt; &lt;/div&gt;
&lt;/div&gt;
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Note: To use the  <code>wp_star_rating()</code> function, you need to require the <code>wp-admin/includes/template.php</code> file as above.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Finally, if you want the star reviews to look better, you should style it a bit. I will enqueue the Dashicons and the <code>frontend.css</code> file as in the method above. Below is the content of the <code>frontend.css</code> file:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>@font-face {
    font-family: "dashicons";
    src: url("../fonts/dashicons.eot");
}
@font-face {
    font-family: "dashicons";
    src: url(data:application/x-font-woff;charset=utf-8;base64,) format("woff"),
        url("../fonts/dashicons.ttf") format("truetype"),
        url("../fonts/dashicons.svg#dashicons") format("svg");
    font-weight: normal;
    font-style: normal;
}
 
.star-rating .star-full:before {
    content: "\f155";
}
 
.star-rating .star-half:before {
    content: "\f459";
}
 
.star-rating .star-empty:before {
    content: "\f154";
}
 
.star-rating .star {
    color: #0074A2;
    display: inline-block;
  font-family: dashicons;
    font-size: 20px;
    font-style: normal;
    font-weight: 400;
    height: 20px;
    line-height: 1;
    text-align: center;
    text-decoration: inherit;
    vertical-align: top;
    width: 20px;
}
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To display the results to the website, simply insert the following code in your theme's <code>single.php</code> file or anywhere you want to display:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<pre>rwmb_the_value( 'rating' );
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And this is the image of the star review on the frontend of mine:</p>
<p><img class="aligncenter" src="https://i.imgur.com/Yd33ACh.png" alt="Display the star ratings on the frontend of the WordPress website" width="1344" height="657" /></p>
<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>And that’s all!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Last Words</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I have shown you how to add star ratings by custom fields with Meta Box plugin through 5 steps. I firmly believe that these star reviews will help your websites, especially your review sites have become more prestigious and professional.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Good luck!</p>