So I am trying to click a custom button I made in a meta box the fire off AJAX. All works except getting the ID of the post and the refreshing of the page. I have tried using global $post; $post_id = $post->ID
or $post_id = $_POST['post_id'];
or $post_id = get_the_ID();
, none of these work.
What I was trying to accomplish eventually is: after clicking the button, a popup happens with "are you sure?"Yes/No. If I click Yes, to change Status function fires and refreshes the post page with status changed.
I am using an Ajax Get with the URL of behind my button: /wp-admin/admin-ajax.php?action=ew_change_status
Reference: Trying to load content of a post via AJAX
This is my functions.php code:
add_action( 'wp_ajax_change_status', 'ew_change_status' );
function ew_change_status() {
//$post_id = $_POST['post_id'];
//$post_id = get_the_ID();
global $post;
global $user_ID;
$post_id = $post->ID;
var_dump($post_id);
remove_filter( current_filter(), __FUNCTION__ );
//Show popup
// ...
// Update Status
$my_post = array(
'ID' => $post_id,
'post_status' => 'status-pending',
);
// Update custom field with User Id
update_post_meta($post_id, 'post_key', $user_ID);
//echo "Updated";
// Update the post into the database
wp_update_post( $my_post );
//wp_redirect(); //Same Page?
//exit;
}
wp-admin/admin-ajax.php
, the$post
object isnull
and so doesget_queried_object()
, because there's no queried object - unlike for example, when loading a post page, the queried object is a post. So you might want to send the post ID from your AJAX script (JS).admin_notices
action it seems to work somewhat.admin_notices
is fired later; but thewp_ajax_xxx
is fired earlier before the$post
is setup. Tryvar_dump( did_action( 'admin_notices' ) );
from thewp_ajax_xxx
callback.