Cannot access current post’s ID in custom plugin

I have a plugin that prepends an upvote box to the_content of a single post, sends data via AJAX back to the main plugin PHP file and calls a function to update a database value on success.

Here is the PHP callback from the AJAX:

function update_parlay_points() {
    //Update Parlay Points field on database with points from Post request. 
    //global $post;
    //$post_id = $post->ID;     
    $post_id = get_the_ID();
    $points = $_POST['score'];      
    $update_points = "UPDATE wp_posts 
        SET parlay_points="$points" 
        WHERE id = $post_id";   
    var_dump( $post_id );
    echo $update_points;           
    global $mysqli;
    $mysqli->query( $update_points ) or die( "Query failed" );
    wp_die();
}

In Chrome’s Developer tools, this gives me:

bool(false) UPDATE wp_posts SET parlay_points=”26″ WHERE id = Query
failed

As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop. The content that triggers the AJAX request is prepended to the_content, so I am not sure if I need to “enter” the Loop again somehow. I tried if ( have_posts() ) and if ( is_single() ) before get_the_ID() with no success. The Loop, in general, really confuses me.

I have also tried accessing $post->ID from the action hook the_post. Strangely enough, I am able to successfully echo the current post’s ID but cannot store it in a globally scoped variable.

$post_id = Null;
add_action( 'the_post', 'wp_store_post_info' );
function wp_store_post_info() {
    //Set current post as global variable. 
    global $post;
    global $post_id;
    $post_id = $post->ID;
    echo $post_id;
}
function update_parlay_points() {
    //...
    global $post_id;
    //Do stuff with the $post_id...
}

This does not work either:

$GLOBALS['post_id'] = $post->ID;

I am certain that the above function is being called, because the correct $post_id is being echoed. However, when I click the upvote button I get:

NULL UPDATE wp_posts SET parlay_points=”28″ WHERE id = Failed Query

3 Answers
3

As you can see, I tried declaring the $post variable as global to account for failures due to being outside of the Loop.

The problem is not that the post is “outside of the loop”, problem is that AJAX request is a completely separate HTTP request.

When you do an AJAX request, is just like you are opening a new window on browser and open the url in this separate window. It means that the script that handles the AJAX request knows nothing about the page that sent the request.

If you need to process a specific post in the AJAX request, you need to send the post ID to process as part of the AJAX request data.

Leave a Comment