catthr
3/30/2015 - 1:07 PM

Ajax запросы в Wordpress

Ajax запросы в Wordpress

function plural_noun($n, $forms){
    return $n%10==1&&$n%100!=11?$forms[0]:($n%10>=2&&$n%10<=4&&($n%100<10||$n%100>=20)?$forms[1]:$forms[2]);
}

add_action( 'wp_ajax_ajax-like', 'bah_add_like' );
add_action( 'wp_ajax_nopriv_ajax-like', 'bah_add_like' );

function bah_add_like() {
    check_ajax_referer( 'ajaxlike-nonce', 'security' );
    $likes_count = intval(get_field('количество_лайков', 'options'));
    $likes_count++;
    update_field('количество_лайков', $likes_count, 'options');
    $res['likes_count'] = $likes_count;
    //так
    echo json_encode($res);
    die;
    //или так
    wp_send_json($res);
}
<span class="stLarge js-ajax-like" 
    data-url="<?= admin_url( 'admin-ajax.php' ) ?>" 
    data-action="ajax-like" 
    data-security="<?= wp_create_nonce('ajaxlike-nonce') ?>">
</span>
 $('.js-ajax-like').click(function(e){
        e.preventDefault();
        var $this = $(this);
        var data = {
            action: $this.data('action'),
            security: $this.data('security')
        };
        $.post($this.data('url'), data, function(response){
            yaCounter27458178.reachGoal('PLUS');
            updateLikesCount(response);
        }, "json");
    });
    
function updateLikesCount(response){
    $('.js-likes_count_text').text(response.text);
    var count = response.likes_count + "";
    var skip = 5 - count.length;
    for(var i=0; i < count.length; i++){
        $('.js-likes_count div').eq(skip + i).text(count[i]);
    }
}