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