Advertisement
Barbareshet

Add star reviews to your posts programatically

Jun 14th, 2020
1,154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.12 KB | None | 0 0
  1. <?php
  2. //Helper function check if value is int or float
  3. function is_decimal($val){
  4.  
  5.         return is_numeric( $val ) && floor( $val ) != $val;
  6.     }
  7.  
  8. if ( !function_exists('my_stars_rating')){
  9.     function my_stars_rating( $content ){
  10.         global $post;
  11.  
  12.         $stars_count = get_post_meta($post->ID,'total_score', true);
  13.         if ($stars_count){
  14.             ob_start() ?>
  15.             <h3 class="ctr-title"><?php printf( __('The rating for this post is %s', 'textdomain'), $stars_count );?></h3>
  16.             <ul class="ctr-stars-list">
  17.                 <?php
  18.                 if ( is_decimal($stars_count) ){
  19.                     for ($i = 1; $i <= ($stars_count); $i++){
  20.  
  21.                         echo '<li class="ctr-star"><i class="fas fa-star" aria-hidden="true"></i></li>';
  22.  
  23.                     }
  24.  
  25.                     echo '<li class="ctr-star"><i class="fas fa-star-half" aria-hidden="true"></i></li>';
  26.  
  27.                 } else {
  28.                     for ($i = 1; $i <= $stars_count; $i++){
  29.  
  30.                         echo '<li class="ctr-star"><i class="fas fa-star" aria-hidden="true"></i></li>';
  31.  
  32.                     }
  33.                 }
  34.                 ?>
  35.             </ul>
  36.             <?php
  37.             return ob_get_clean();
  38.         }
  39.         if ( is_single() ){
  40.             return $content.$stars_count;
  41.         }
  42.     }
  43.  
  44. }
  45.  
  46.  
  47. add_filter('the_content', 'my_stars_rating');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement