DEV Community

Cover image for Add Star Ratings to WordPress on the Backend Using Custom Fields
WP Meta Box Plugin
WP Meta Box Plugin

Posted on • Originally published at metabox.io

Add Star Ratings to WordPress on the Backend Using Custom Fields

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 theme review page.

To help the website owner to add star ratings on their review website, you can use custom fields and create a plugin yourself to add star ratings. That is the topic of today's tutorial.

First of all, you need to download and install Meta Box plugin - a framework for creating custom fields. This Meta Box core plugin is free at wordpress.org. After downloading, start working on it.

Step 1: Create a New Plugin to Add Star Ratings

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.

I name this plugin MB Rating Field.

First, we start building this new plugin with the directory structure like so:

wp-content / plugins / mb-rating-field
  - css
  - admin.css
  - frontend.css
rating.php
mb-rating-field.php

In it, the mb-rating-field.php file has the following content:

 ? php
/ **
* Plugin Name: MB Star Rating
* URI plugin: https://metabox.io
* Description: Add a new star rating field type for Meta Box
* Version: 1.0
* Author: MetaBox.io
* Author URI: https://metabox.io
* License: GPLv2
* /

Then, activate this plugin in the list of installed plugins in the Dashboard.

Install the new plugin to add star ratings to WordPress on the backend

Next, we are going to start building the function to create custom fields for the star rating feature of this plugin, following these steps:

Step 2: Create a Field Type to Add Star Ratings

In this step, we will create a new field type called rating to add star ratings.

First, create a class named RWMB_Rating_Field for this rating field. Usually, if you want to create a certain type of field, you should create a class with the syntax RWMB _ {$ field_type} _Field. You can see more details in this guide of Meta Box.

if (class_exists ('RWMB_Field')) {
    class RWMB_Rating_Field extends RWMB_Field {}
}

Next, save this class to a PHP file (for example, I save it in the rating.php file), then put this file in the plugin mb-rating-field.php file created in Step 1.

add_action ('init', 'prefix_load_rating_type');
function prefix_load_rating_type () {
    require __DIR__. '/rating.php';
}

Step 3: Create Options to Add Star Rating for the Rating Field

Once you have the rating field, you need to create options that allow website owners to score stars (from 0.5 to 5 stars).

This rating class will inherit all the methods of the RWMB_Field class. In this rating field, we must specify the content of the html method to output the HTML in the backend.

Do it by adding the following code to the rating.php file.

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

Here, we use the "radio" field type to give the user a 0.5 to 5 band score to rate.

Next, we need to style a little to show the above radio options as stars (currently they are only visible as small circles).

Create Options to Add Star Rating for the Rating Field

Just add this code to the css/admin.css file.

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

To get the style in admin, we use the function admin_enqueue_scripts () to enqueue. Please enqueue in the rating.php file as follows:

public static function admin_enqueue_scripts() {
wp_enqueue_style( 'rwmb-rating', plugin_dir_url( __FILE__ ) . '/css/admin.css', array(), '1.0.0' );
}

The rating.php file has this content: https://github.com/elightup/mb-rating-field

Step 4: Create Custom Fields to Add Star Ratings with MB Star Rating Plugin

Now, we can create custom fields with rating field type using the newly created MB Star Rating plugin!

You just need to put the following code in the functions.php file of your theme or child theme, note that 'type' => ‘rating' is set as follows:

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

Now, when you go to the post / page editor, you will see the created custom field display as follows:

The custom fields to add star ratings created by MB Star Rating plugin

And just enter the name and rate:

Enter the name and rate by the star rating field

Step 5: Display The Star Ratings on The Frontend

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 wp_star_rating () function.

In the rating.php file, you use the format_single_value () method by adding this code:

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' => $starrating,
             'type' => 'rating',
       );
       wp_star_rating( $args );

The above code will output the following HTML in the frontend:

<div class = "star-rating" title = "" Number of stars obtained "rating">
     <div class = "star star-full"> </div>
     <div class = "star star-full"> </div>
     <div class = "star star-full"> </div>
     <div class = "star star-half"> </div>
     <div class = "star star-empty"> </div>
</div>

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

Finally, if you want the star reviews to look better, you should style it a bit. I will enqueue the Dashicons and the frontend.css file as in the method above. Below is the content of the frontend.css file:

@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;
}

To display the results to the website, simply insert the following code in your theme's single.php file or anywhere you want to display:

rwmb_the_value( 'rating' );

And this is the image of the star review on the frontend of mine:

Display the star ratings on the frontend of the WordPress website

And that’s all!

Last Words

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.

Good luck!

Top comments (0)