Leave a Reply

2 comments

  1. Couple of things:

    1: When you include the script after jquery, localise it using the wp_localize_script function:

    $nonce = wp_create_nonce("vote_nonce");
    $yourscript_info = array(
        'ajaxurl' => admin_url( 'admin-ajax.php'),
        'nonce' => $nonce
    );
    wp_localize_script( 'yourscript', 'yourscript', $yourscript_info );
    
    $.ajax({
        type: "POST",
        url: yourscript.ajaxurl,
        data: { id: id, vote: vote, nonce: yourscript.nonce, action: "stn_voting" },
    

    2: Add some security checks using a nonce:

    function ajax_stn_voting() {
        //simple Security check
        if ( ! wp_verify_nonce( $_POST['nonce'], 'vote_nonce' ) )
            die ( 'Busted!');
    

    3: You don’t need to include the post id in the meta keys. Its already attached to the post, so its already stored in the database.

    $key = 'vote_up';
    instead of
    $key = 'vote_up_' . $post->ID;
    

    Not just the vote_up key, but all of the _’ . $post->ID; part is unnecessary inside the function. If all of your keys are different, you can’t order the posts based on these values and its simply an unnecessary thing to do.

    4: You need to “die” at the end of the function when you’re using ajax:

        die();
    }
    add_action('wp_ajax_stn_voting', 'ajax_stn_voting');
    add_action('wp_ajax_nopriv_stn_voting', 'ajax_stn_voting');
    

    Otherwise, the script looks good to me.

    And what G. M. said in the comments above:)