Posted on Leave a comment

WordPress: Best Plugin to improve your website speed in google

Today I wasted many hours to increase my website’s speed in google PageSpeed insights but I could not. I was in red color. But then I found following plugin that surprisingly increased my page speed. And now that website entered in Green on google:

Plugin: GZip Ninja Speed

URL: https://wordpress.org/plugins/gzip-ninja-speed-compression/

Further I would like to share my final .htaccess file to you. May that can also help you to reach green color for your web speed in google:


# BEGIN WordPress
 
<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler   ^cgi-script$
    mod_gzip_item_include mime      ^text/.*
    mod_gzip_item_include mime      ^application/x-javascript.*
    mod_gzip_item_exclude mime      ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^download/(.+)$ /wp-content/force-download.php?file=uploads/$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Header set Connection keep-alive

FileETag none



## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType text/x-js "access plus 1 month"
ExpiresByType application/x-js "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>


<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

# BEGIN W3TC Browser Cache
<IfModule mod_mime.c>
    AddType text/css .css
    AddType text/x-component .htc
    AddType application/x-javascript .js
    AddType application/javascript .js2
    AddType text/javascript .js3
    AddType text/x-js .js4
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg .svgz
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType application/json .json
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/x-font-otf .otf
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType application/x-font-ttf .ttf .ttc
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
</IfModule>
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>
<IfModule mod_deflate.c>
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
        AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json
    <IfModule mod_mime.c>
        # DEFLATE by extension
        AddOutputFilter DEFLATE js css htm html xml
    </IfModule>
</IfModule>
<FilesMatch "\.(css|htc|js|js2|js3|js4|CSS|HTC|JS|JS2|JS3|JS4)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "public"
         Header set X-Powered-By "W3 Total Cache/0.9.3"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|SVGZ|TXT|XSD|XSL|XML)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "public"
         Header set X-Powered-By "W3 Total Cache/0.9.3"
    </IfModule>
</FilesMatch>
<FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|WAV|WMA|WRI|XLA|XLS|XLSX|XLT|XLW|ZIP)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header append Cache-Control "public"
         Header set X-Powered-By "W3 Total Cache/0.9.3"
    </IfModule>
</FilesMatch>
## EXPIRES CACHING ##

ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/x-js "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"

## EXPIRES CACHING ##
# GZip Ninja Speed -- Starts here
# Do not write anything between "GZip Ninja Speed -- Starts" and "GZip Ninja Speed -- Ends"
# It will be deleted while uninstalling GZip Ninja Speed plugin
AddOutputFilterByType DEFLATE text/plain #GZip Ninja Speed
AddOutputFilterByType DEFLATE text/html #GZip Ninja Speed
AddOutputFilterByType DEFLATE text/xml #GZip Ninja Speed
AddOutputFilterByType DEFLATE text/css #GZip Ninja Speed
AddOutputFilterByType DEFLATE application/xml #GZip Ninja Speed
AddOutputFilterByType DEFLATE application/xhtml+xml #GZip Ninja Speed
AddOutputFilterByType DEFLATE application/rss+xml #GZip Ninja Speed
AddOutputFilterByType DEFLATE application/javascript #GZip Ninja Speed
AddOutputFilterByType DEFLATE application/x-javascript #GZip Ninja Speed
AddType x-font/otf .otf #GZip Ninja Speed
AddType x-font/ttf .ttf #GZip Ninja Speed
AddType x-font/eot .eot #GZip Ninja Speed
AddType x-font/woff .woff #GZip Ninja Speed
AddType image/x-icon .ico #GZip Ninja Speed
AddType image/png .png #GZip Ninja Speed
# GZip Ninja Speed -- Ends here

 

Posted on Leave a comment

WordPress: Best Plugins to migrate website form one hosting to another hosting

Alright! Today I found an awesome, very useful and time saving plugin that can save your a lot of time if you are willing to migrate your wordpress website from one server to remote server.

Just install this plugin: Welcome to WP Clone by WP Academy

First install this plugin in first server.

Take backup and copy url of zip file of created backup.

Install WordPress in remote hosting. Install above plugin and paste the copied url in the input to import webste remotely from the WP Clone menu.

It takes just around 2 minutes to shift whole wordpress website including database and all settings.

Before this it used to take a lot of time to shift website. I used to face several technical issues.
But this method is very time saving. You don’t have to be technical at all to shift a website with this plugin.

Posted on Leave a comment

WordPress: How to display custom taxonomy terms in select field in options panel of redux framework?

bwNAorV

Its very easy to show custom taxonomies as select options list in the options panel of redux framework.

I used following paremeter to get list of custom taxonomies:

 'fields'     => array(
                 array(
                'id'          => 'slider_type',
                'type'        => 'select',
                'title'       => __( 'Select Slider for Homepage', 'redux-framework-demo' ),
                'subtitle'    => __( '' ),
                'desc'        => __( 'Above you will select the slider from the list of slider types which you created.', 'redux-framework-demo.', 'redux-framework-demo' ),
                'data'        => 'terms',
                'args'        =>  array('taxonomies'=>'slidertype', 'args'=>array('hide_empty'=>0)),
            ),
       )

 

Posted on Leave a comment

WordPress: how to add custom classes in wp_nav_menu using custom walker calass?

Sometimes we need to add custom classes in the the navigation menus created by wordpress’ function ‘wp_nav_menu’. For example we want to add custom classes for dropdown menus, in such spcific cases we there is no option to add custom class for dorpdown menu. So in that case we can use walker abstract class.
We will create a new class in functions.php extending wordpress class “Walker_Nav_Menu” of  “Walker” Class. We can set any name to our new walker class. i.e. Primary_Walker_Nav_Menu

Example:

Class: Primary_Walker_Nav_Menu in functions.php

// walker class to add custm classes in the header menu
class Primary_Walker_Nav_Menu extends Walker_Nav_Menu {

function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
    $output = str_replace("menu-item-has-children", "menu-item-has-children dropdown", $output);
  }
}

Navigation Menu Function: wp_nav_menu

 $defaults = array(
              'theme_location'  => 'primary',
              'menu'            => '',  // name of the menu you created in the menus
              'container'       => '',
              'container_class' => '',
              'container_id'    => '',
              'menu_class'      => '',
              'menu_id'         => '',
              'echo'            => true,
              'fallback_cb'     => 'wp_page_menu',
              'before'          => '',
              'after'           => '',
              'link_before'     => '',
              'link_after'      => '',
              'items_wrap'      => '<ul id="%1$s" class="%2$s nav navbar-nav navbar-right menu">%3$s<li class="search"></li></ul>',
              'depth'           => 0,
              'walker'          => new primary_Walker_Nav_Menu() // this is the walker class we created to alter default menu html
            );
           
             wp_nav_menu( $defaults );

 

Posted on Leave a comment

how to create custom admin page?

In this article I’ll show how to create custom page for admin panel.

<?php

// Following code is just example to show how this works. So obviously you can alter this or write your own code for UI

// function that will prpeare User Interface for our New Admin Page
function az_admin_custom_page() // You can set any name whatever you want 
{
  global $wpdb; // this is required so that you can use wordpress to execute your sql queries

  $sql="SELECT *  FROM table";
  $rows= $wpdb->get_results($sql);

?>
   <div class="wrap">
        <h2><span class="dashicons dashicons-admin-comments"></span> Page Heding</h2> 
        <form method="POST" action="">
            <table class="wp-list-table widefat fixed">
                <thead>
                  <tr>
                    <th scope="col" id="username" class="manage-column column-username" style="">
                       Name  
                    </th>
                    <th scope="col" id="account" class="manage-column column-account" style="">Comment</th>
                    <th style="width:20%" scope="col" id="cb" class="manage-column column-cb check-column" style="">
                      Rating
                    </th>
                    <th>Class</th>
                    <th>Merchant</th>
                    <th style="width:10%">

                    </th>
                    
                  </tr>
				        </thead>
              <tbody id="the-list">
                <?php
                foreach($rows as $review)
                {


                ?>            
                <tr id="review_<?php echo $review->id;?>" class="<?php echo $review->id_post;?>">
                  <td><?php echo $review->name;?></td>
                  <td><?php echo $review->comment;?></td>
                  <td><?php echo $review->rate;?>/5</td>
                  <td><?php echo $review->class;?></td>
                  <td><?php echo $review->merchant;?></td>
                  <td><a data-id="<?php echo $review->id;?>" class="delete" href="javascript:void(0)">Delete</a></td>
                </tr>
                <?php
              }
              ?>
              </tbody>
            </table>
   <?php
                    
}

 

Posted on Leave a comment

How to setup Google reCaptcha Version 2.0?

Screenshot_4

To setup Google reCaptcha oepn url https://www.google.com/recaptcha/admin and fill form as shown in the screenshot below:

After registration open newly created reCaptcha site and read the guide provided by google as shown below:

Screenshot_3

Now paste <script src=’https://www.google.com/recaptcha/api.js’></script>  in <head> or anywhere before use of captcha.

And then paste <div class=”g-recaptcha” data-sitekey=”6LcPQggTAAAAAAw-SQm8KTEW-N1CBuzBz_gW71UT”></div> to the place where you want to show captcha in form and obviously you will have to use tag with your own site key from google reCaptcha site.

Continue reading How to setup Google reCaptcha Version 2.0?

Posted on Leave a comment

WordPress: How to submit custom form data using Ajax?

In wordpress we send data using same ajax method as we do in regular non-wordpress website.  The difference is few additional data variables and filter on serverside.

To Implement this I created a template page named “Request a Quote” in request-a-quote.php, created new wordpress and assigned that template to this page.

Screenshot_1

Continue reading WordPress: How to submit custom form data using Ajax?

Posted on Leave a comment

How to create Custom 5 Stars Rating System in WordPress?

Screenshot_3

In this article I’ll show that how to create custom 5 stars Rating system in wordpress.

I’ll create WordPress Short Code to place rating anywhere in any post.

Steps:

1- Create Directory “az_rating” in the root folder of your active theme.

2- Create rating.php in az_rating/ folder. In this file we will write all code for the forntend of the rating system. and add this image in az_rating/ folder:

star   Download this image in required folder.

3- Open functions.php file from the root folder of your active theme. Or create functions.php file if it does not exist.

Database Table:

Screenshot_1

4- Create a table az_rating in your current wordpress database. Run following SQL to create the table:

--
-- Table structure for table `az_rating`
--

CREATE TABLE IF NOT EXISTS `az_rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_post` int(11) NOT NULL,
  `ip` varchar(40) NOT NULL,
  `rate` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `comment` text NOT NULL,
  `dt_rated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=38 ;

5- rating.php:

CSS code for rating styles:

<style>
   #reviews
   {
   padding-left:30px;
   }
   #reviews_list
   {
   max-height: 422px;
   overflow: auto;
   padding-right: 10px;
   text-align: left;
   margin-top: 19px;
   }
   .item {
   margin-bottom: 10px;
   border-bottom: 1px solid rgb(204, 204, 204);
   padding-bottom: 10px;
   }
   #comment_form .stars {
   margin-top: 10px;
   margin-bottom: 10px; cursor: pointer;  
   }
   #comment_form .star
   {
     width: 31px;
  height: 20px;  background-size: 27px 43px;
   }
      #comment_form h3
      {
        margin-top:20px; margin-bottom:10px;
      }
   #comment_form input.form-control, textarea {
   margin-bottom: 10px; padding:10px;
   }
   .reviews_content
   {
   padding-left:30px; 
   }

   #comment_form .star:hover, .star.active {
   background-position: top;
}

.star {
  width: 15px;
  height: 15px;
  background-image: url('<?php echo $base_url; ?>/az_rating/star.png');
  background-size: 17px 30px;
  background-position: bottom;
  display: inline-block;
}
</style>

jQuery Code:

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
   $(document).ready(function(){
       $("#comment_form .star").click(function() {
               apply_rating(this);
       });
   
       $("#comment_form .submit").click(function() 
           {
              // disable the submit button to avoid multiple submission
               $(this).off();
               $(this).attr("disabled","disabled");
   
               // Call this function to start save process
               save_rating(this);
           }
           );
   });
   
   // this function will save rating to database and refresh the current view
   function save_rating()
   {
   
      // getting the star rating 
       var total_rating = $("#comment_form .star.active").length;
       var name = $("#comment_form input[name=name]").val();
       var comment = $("#comment_form textarea[name=comment]").val();
      
      // preparing the new review html
       var review = '<div class="item" style="display:none"><div class="comment">'+comment+'</div><div class="name">'+name+'</div>';
   
   
      // adding stars in the new reivew html
       for(var i=0; i<6; i++)
       {
           if( total_rating>0)
           {
               var extClass="";
               if(i<=total_rating)
               {
                   extClass="active";
               }
               review = review+'<div class="star '+extClass+'"></div>';
           }
           
       
              review = review+"</div>";
   
      
   
       // this is required url for ajax calls in the wordpress
       var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
   
       /* 
       *
       * "action" is the name of the action which you set up in the functions.php that 
       * will call a function to submit rating
       *
       * "get_the_ID()" will fetch the current post ID
       *
       */


   
       var data={'id_post':"<?php echo get_the_ID(); ?>", action:'submit_rating', rating:total_rating, name:name, comment:comment}
      
      $.post(ajax_url, data, function(response) {
          
            // after completion show the newly added review
           $("#reviews_list").prepend(review);
           $("#reviews_list .item:first-child").slideDown();
           $("#comment_form").slideUp();
           $("#comment_form").remove();
           $("#rating_status").slideDown();
            
            // preparing data for another ajax call
            // this ajax function will refresh the main rating to show latest calcultions
            var data={'id_post':"<?php echo get_the_ID(); ?>", action:'get_latest_rating'}
   
            $.post(ajax_url, data, function(response) {
               
               $("#reviews").html(response);
   
            });
           
       });// end wp ajax
   }
   
   // this function will be called when user select star out of five star on click to fill the star according to the selected rating 
   function apply_rating(element)
   {
       
       var total_rating = $(element).index()+1;
   
        $("#comment_form .star").removeClass('active');
           
           for(var i = 0; i<total_rating; i++)
           {
               $('#comment_form .star').eq(i).addClass('active');
           }
   
   }
</script>

HTML Section:

<!-- Main Reviews -->
<div style="cursor:pointer" onclick="$('.reviews_content').slideDown()" id="reviews" class="'.$reviews_container_class.'" style="text-align:right;">
   <div class="star <?php echo ($rating>=1)? "active":""?>"></div>
   <div class="star <?php echo ($rating>=2)? "active":""?>"></div>
   <div class="star <?php echo ($rating>=3)? "active":""?>"></div>
   <div class="star <?php echo ($rating>=4)? "active":""?>"></div>
   <div class="star <?php echo ($rating>=5)? "active":""?>"></div>
   <span>
      <totalReviews><?php echo $reviews_total; ?></totalReviews>
      Review(s)
   </span>
</div>
<div class="reviews_content" style="display:none;">
   <!-- list of rating and comments -->
   <div id="reviews_list" class="row" >
      <div class="col-xs-12">
         <?php
            foreach($reviews as $review)
            {
            ?>
         <div class="item">
            <div class="comment"><?php echo $review->comment;?></div>
            <div class="name"><?php echo $review->name; ?></div>
            <div class="star  <?php echo ($review->rate>=1)? "active":""; ?>"></div>
            <div class="star  <?php echo ($review->rate>=2)? "active":""; ?>"></div>
            <div class="star  <?php echo ($review->rate>=3)? "active":""; ?>"></div>
            <div class="star  <?php echo ($review->rate>=4)? "active":""; ?>"></div>
            <div class="star  <?php echo ($review->rate>=5)? "active":""; ?>"></div>
         </div>
         <?php
            }
            ?>
      </div>
   </div>
   <?php
      $rated = false;
      // adding ip restriction
      // following code will check to see if current user already rated this post or not
      // if user already rated then this sicript will simple hide the form to leave review
      foreach($reviews as $review_row)
      {
          if($review_row->ip==$_SERVER['REMOTE_ADDR'])
          {
              $rated = true;
          }
      }
                  if($rated==false)
                  {
      ?>
   <div id="comment_form">

      <h3>Leave your Review</h3>
      <div class="stars">
         <div class="star"></div>
         <div class="star"></div>
         <div class="star"></div>
         <div class="star"></div>
         <div class="star"></div>
      </div>

      <div class="row">
         <div class="col-xs-12">
            <input name="name" class="form-control" placeholder="Full Name">
         </div>
      </div>
      <div class="row">
         <div class="col-xs-12"> 
            <textarea class="form-control" placeholder="Your Comment" name="comment"></textarea>
         </div>
      </div>
      <div class="row">
         <div class="col-xs-12">
            <button  class="btn btn-success submit" type="button">Submit Review</button>
         </div>
         <br>
      </div>
   </div>

   <div style="font-size:15px; display:none; font-style:italic;  text-align:right; color:green; font-weight:bold; margin-top:20px;" id="rating_status">Thanks for Rating!</div>

   <?php
      }
      ?>
</div>

functions.php:

In this file we will create three functions for our reviews system:

  • az_rating()
    This function will create short code “[az_rating]”
  • submit_rating_callback()
    This function will submit review to the database and will update User Interface accodingly.
  • get_latest_rating_callback()
    This function will get the latest rating by given post id.

Put following functions at the end of this file.

6- Creating shortcode:

First of all we’ll create a wordpress shortcode function.

az_rating() function will create complete functionality for short code. We named our short code as az_rating.

function az_rating( $atts ){
	$base_url = get_stylesheet_directory_uri();
 	global $wpdb;


 	// fetching all reviews from database
 	# get_the_ID() function will just get the id of the current post in which short code is placed
    $sql="SELECT *  FROM az_rating where id_post='".sanitize_text_field(get_the_ID())."'";

    $reviews = $wpdb->get_results($sql);
    $reviews_total = count($reviews);

    // calculationg average of the ratings
    $sql="SELECT avg(rate) as avg FROM az_rating where id_post='".sanitize_text_field(get_the_ID())."'";

    $result = $wpdb->get_results($sql);
    $rating = round($result[0]->avg);

    // Loading HTML Interface into variable so we can return
	ob_start();
	include("az_rating/rating.php");
	$review_content = ob_get_contents();
	ob_end_clean();
 

	return $review_content;
}
add_shortcode( 'az_rating', 'az_rating' );

7- Function to submit rating in the databse:

submit_rating_callback():

This function will receive data from the review form through ajax.

We created custom action for ajax handling and called above function with that action call:

// add the custom action used for ajax call
add_action('wp_ajax_submit_rating', 'submit_rating_callback');
// if you are using ajax on frontend for non-authenticated users then must use following action otherwise ajax will not work as expected
add_action('wp_ajax_nopriv_submit_rating', 'submit_rating_callback');
// this function will submit rating to database. This function will be called by ajax from review form
function submit_rating_callback()
{
    global $wpdb;
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $id_post    = sanitize_text_field($_POST['id_post']);
    $rating     = sanitize_text_field($_POST['rating']);
    $name       = sanitize_text_field($_POST['name']);
    $comment    = sanitize_text_field($_POST['comment']);
    
    // checking if this post was rated before or not
    $sql = "SELECT count(id) as total FROM az_rating where id_post='" . $id_post . "' and ip='" . $ip_address;
    
    $posts   = $wpdb->get_results($sql);
    $reviews = $posts[0]->total;
    
    if ($reviews < 1) {
        echo $wpdb->show_errors();
        $result = $wpdb->insert('az_rating', array(
            'id_post' => $id_post,
            'ip' => $ip_address,
            'rate' => $rating,
            'name' => $name,
            'comment' => $comment
        ));
        
        
        echo $wpdb->show_errors();
        if ($result) {
            echo "done :)";
        }
        
    }
    
    wp_die();
    
}

8- Geting latest stars-rating to update in user interface:

get_latest_rating_callback():

This function will be called to get latest stars-rating through get_latest_rating action.

add_action('wp_ajax_get_latest_rating', 'get_latest_rating_callback');

// if you are using ajax on frontend for non-authenticated users then must use following action otherwise ajax will not work as expected
add_action('wp_ajax_nopriv_get_latest_rating', 'get_latest_rating_callback');

function get_latest_rating_callback()
{
    global $wpdb;
    echo "asdfad";
    $id_post = sanitize_text_field($_POST['id_post']);
    $sql     = "SELECT *  FROM az_rating where id_post='" . $id_post . "'";
    
    $reviews       = $wpdb->get_results($sql);
    $reviews_total = count($reviews);
    
    $sql = "SELECT avg(rate) as avg FROM az_rating where id_post='" . $id_post . "'";
    
    $result = $wpdb->get_results($sql);
    $rating = round($result[0]->avg);
    
    $reviews = ' <div class="star ' . (($rating >= 1) ? "active" : "") . '"></div>
                        <div class="star  ' . (($rating >= 2) ? "active" : "") . '"></div>
                        <div class="star ' . (($rating >= 3) ? "active" : "") . '"></div>
                        <div class="star ' . (($rating >= 4) ? "active" : "") . '"></div>
                        <div class="star ' . (($rating >= 5) ? "active" : "") . '"></div>
                        <span><totalReviews>' . $reviews_total . '</totalReviews> Review(s)</span>';
    echo $reviews;
    wp_die();
}

Ok now our Reviews system is ready to use.

To use this add this shorcode [az_rating] anywhere inshide the while loop of your post.

If you directly want to use shortcode inside the php code then paste this code in your php script to show review content:

<?php echo do_shortcode(‘[az_rating]’); ?>