// use of shortcode: [cp_reviews url="https://wordpress.org/support/plugin/location-weather/reviews/" target="4.5"] add_shortcode( 'cp_reviews', function( $atts, $content ) { $a = shortcode_atts( array( 'url' => 'https://wordpress.org/support/plugin/post-carousel/reviews/', 'target' => '4.78', ), $atts ); $url = $a['url']; $cp_review_info = get_transient( 'cp_review_info_' . md5($url) ); if ( $cp_review_info ) { $reviews = $cp_review_info[0]; $averageReview = $cp_review_info[1]; $totalReviews = $cp_review_info[2]; } else { $params = array( 'timeout' => 101, 'sslverify' => true, ); $raw = wp_remote_retrieve_body( wp_remote_get( $url, $params ) ); if ( strpos( $raw, 'class="review-ratings">' ) !== false ) { $raw = explode( 'class="review-ratings">', (string) $raw )[1]; } if ( strpos( $raw, '<div class="col-5">' ) !== false ) { $raw = explode( '<div class="col-5">', $raw )[0]; } if ( strpos( $raw, '<span class="counter-count" style="margin-left:5px;">' ) !== false ) { $raw = explode( '<span class="counter-count" style="margin-left:5px;">', $raw ); unset($raw[0]); // Remove plugin name. } $i = 5; $sum = 0; $reviews = array(); foreach( $raw as $review ) { if ( strpos( $review, '</span>' ) !== false ) { $review = explode( '</span>', $review )[0]; $reviews[] = $review; $sum += $i * $review; $i--; } } $totalReviews = array_sum($reviews); $averageReview = $sum / $totalReviews; $review_info = array( $reviews, $averageReview, $totalReviews ); set_transient( 'cp_review_info_' . md5($url), $review_info, 24 * HOUR_IN_SECONDS ); } ob_start(); $target_review = (float) number_format( $a['target'] , 2); $averageReview1 = (float) number_format( $averageReview, 2); for( $j = 0; $averageReview1 < $target_review; $j++ ) { $averageReview1 = ( 5 * ( $reviews[0] + $j ) + 4 * $reviews[1] + 3 * $reviews[2] + 2 * $reviews[3] + 1 * $reviews[4] ) / ( ( $reviews[0] + $j ) + $reviews[1] + $reviews[2] + $reviews[3] + $reviews[4] ); $averageReview1 = (float) number_format($averageReview1, 2); //echo ($averageReview1."<br/>"); } echo "Total Review: " . $totalReviews; echo " | Average Review: " . number_format($averageReview, 2); echo " | Target Review: " . number_format($target_review, 2); echo" | Additional 5-Star Reviews Needed: $j <br/>"; return ob_get_clean(); } );
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter