0

WP-postratings Adds ratings to WP. It's the most downloaded ratings plugin on the repository. Votes are sent via AJAX but the rendering of the plugin is not. As a result when using a caching plugin you see a cached version of the votes, which is bad. I found a solution but it had no effect for me. Can somebody see what's wrong with it?

/**
 * Get WP-PostRatings via ajax
 *
 * Useful when using cache plugins like WP Super Cache or W3 Total Cache
 * 
 */
function ac_get_rating_ajax($postID) {

    // Create nonce - security measure
    $nonce = wp_create_nonce('display-rating');

    // Placeholder HTML that will get replaced when the rating loads
    $out .= '<div id="ac-ratings-wrap-' . $postID . '">';
    $out .= '<p>Just a moment please...</p>';
    $out .= '</div>';

    // Script to get the rating
    $out .= '<script type="text/javascript">';
    $out .= 'jQuery(document).ready(function($) {';
    $out .= '$.ajax({';
        $out .= 'url : "' . admin_url( 'admin-ajax.php' ) . '",';
        $out .= 'dataType: "jsonp", ';
        $out .= 'data : { "id" : "' . $postID . '", "_ajax_nonce" : "' . $nonce . '", action : "ajax_display_rating" }, ';
        $out .= 'success : function(response) { $("#ac-ratings-wrap-' . $postID . '").html(response.output); }';
        $out .= '});';
    $out .= '});';
    $out .= '</script>';

    // Return it
    return $out;

}

// Hook ajax function into admin-ajax.php
add_action( 'wp_ajax_nopriv_ajax_display_rating', 'ac_ajax_display_rating' );
add_action( 'wp_ajax_ajax_display_rating', 'ac_ajax_display_rating' );

// Ajax function
function ac_ajax_display_rating() {

    // Nonce
    $nonce = $_GET['_ajax_nonce'];
    if ( !wp_verify_nonce( $nonce, 'display-rating' ) ) die('Security check');

    // Check Ajax referer
    if ( !check_ajax_referer( 'display-rating', '_ajax_nonce', false ) ) die('Security check');

    global $wpdb;

    // SQL injection protection
    $postID = $wpdb->escape($_GET['id']);
    if ( !is_numeric($postID) ) die('error');

    // Return the rating display (not echo)
    $out = the_ratings( 'div', $postID, false );

    // Encode and echo
    $arr = array( 'output' => $out );

    $arr = json_encode($arr);

    echo $_GET['callback'] . '(' . $arr . ');'; // Callback is generated by jQuery

    exit();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.