Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Update status, meta while inside a post using AJAX button

First things first

In a wp_ajax_{action} or wp_ajax_nopriv_{action} callback, the global $post variable is by default a null because WordPress has not yet set it up. You can confirm it using a simple callback like so:

add_action( 'wp_ajax_test', function(){
    global $post;
    var_dump( $post );
    wp_die();
} );

Visit /wp-admin/admin-ajax.php?action=test and you should see NULL displayed on the page. If you don’t see a NULL, then it’s possible that a plugin or custom code has made a query which changed the $post variable.

Now a solution

Since you’re making the AJAX request via a button click and the button is inside a meta box which I suppose is on the post edit screen (wp-admin/edit.php), then an easy way to fix the issue of the $post being still a NULL in your wp_ajax_change_status callback, is to send the post ID from your AJAX script (JavaScript).

On the post edit screen, the post ID is stored in a hidden input field named post_ID which looks like this and stores the ID of the post that’s currently being edited:

<input type="hidden" id='post_ID' name="post_ID" value="123" />

So you can use the value and send it to your AJAX callback. E.g.:

jQuery.ajax({
    url: '/wp-admin/admin-ajax.php',
    data: {
        action:  'change_status',
        post_id: jQuery( '#post_ID' ).val() // send the post ID
    },
    type: 'post'
});

Then in your AJAX callback (i.e. the ew_change_status() function), you can retrieve the submitted post ID like so:

$post_id = filter_input( INPUT_POST, 'post_id' );

Additional Notes

  1. In your AJAX callback, make sure to check whether the current user can edit the post. E.g.:

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_die();
    }
    
  2. Use a nonce (because you are editing a post). For example,

    a) In your meta box, create a hidden input for storing the nonce:

    // Creates an <input> with the `id` and `name` "my_security".
    <?php wp_nonce_field( 'change-post-status', 'my_security' ); ?>
    

    b) Include the nonce in the AJAX request:

    jQuery.ajax({
        url: '/wp-admin/admin-ajax.php',
        data: {
            action:  'change_status',
            post_id:  jQuery( '#post_ID' ).val(),
            security: jQuery( '#my_security' ).val()
        },
        type: 'post'
    });
    

    c) In your AJAX callback, verify the nonce:

    check_ajax_referer( 'change-post-status', 'security' );
    

So your ew_change_status() may look like:

function ew_change_status() {
    check_ajax_referer( 'change-post-status', 'security' );

    $post_id = filter_input( INPUT_POST, 'post_id' );
    if ( ! $post_id || ! ( $post = get_post( $post_id ) ) ) {
        wp_die( 'No such post, or invalid ID.' );
    }

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_die( 'You can not edit this post.' );
    }

    ... your code here ...

    wp_die();
}

Related Posts:

  1. Long Polling: Stuck in while loop
  2. How to update Comment post meta through an Ajax call
  3. Update attachment metadata fails
  4. Attach time/date stamp on add_post_meta
  5. wp_update_post onclick button using ajax
  6. bulk update meta value with ajax
  7. Filter images from media library by guid meta field
  8. Want to send ajax request in wordpress to a custom file in plugin
  9. delete post meta data in array WordPress
  10. Allow guest to update custom post met using ajax
  11. Data from ajax not updating post meta
  12. delete attachment for one post without deleting actual attachment post
  13. add_post_meta not working within AJAX function
  14. PHP “php://input” vs $_POST
  15. Google Maps API throws “Uncaught ReferenceError: google is not defined” only when using AJAX
  16. Access-Control-Allow-Origin error sending a jQuery Post to Google API’s
  17. Access-Control-Allow-Origin error sending a jQuery Post to Google API’s
  18. How to solve the error “SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.” in IE
  19. Show spinner GIF during an $http request in AngularJS?
  20. Refresh HTML Page in Browser Automatically on Timer – Every 15 Min
  21. JavaScript implementation of Gzip
  22. jQuery: Performing synchronous AJAX requests
  23. ASP.NET MVC controller actions that return JSON or partial html
  24. jQuery’s .on() method combined with the submit event
  25. Ajax takes 10x as long as it should/could
  26. How to check if I am in admin-ajax.php?
  27. Best way to end WordPress ajax request and why?
  28. How to load wp_editor() through AJAX/jQuery
  29. How to cache json with wp-super cache
  30. Load minimum WordPress environment
  31. Why use wp_send_json() over echo json_encode()?
  32. Why use admin-ajax.php and how does it work?
  33. How to get a unique nonce for each Ajax request?
  34. Open a Thickbox with content trough AJAX
  35. Initialize TinyMCE editor / visual editor after AJAX insert
  36. Why not register shortcodes if is_admin dashboard?
  37. WordPress AJAX with Axios
  38. Why is die() used at the end of function that handles an Ajax request?
  39. Why might a plugin’s ‘do_shortcode’ not work in an AJAX request?
  40. Making my AJAX powered WordPress Crawlable
  41. Is there a JavaScript API? How to access public and private data in JS?
  42. Get Previous & Next posts by Post ID
  43. failed to load wp-admin/admin-ajax.php
  44. Using Backbone with the WordPress AJAX API
  45. Using Ajax with a Class file
  46. Ajax in a settings page (update_option is undefined)
  47. How to pass data parameter to ajax action function handler
  48. WordPress Ajax Data Security
  49. post formats – how to switch meta boxes when changing format?
  50. Displaying PHP Errors from admin-ajax.php
  51. wp_set_auth_cookie() doesn’t work in Ajax call
  52. gettext does not translate when called in ajax
  53. Execute one AJAX request after another AJAX request finished
  54. WP-AJAX vs WP REST API: What to use for requests to the website from outside?
  55. Ajax and autocomplete
  56. How to add to cart via AJAX Woocommerce [closed]
  57. Nonces and Cache
  58. SSL breaks customizer: page isn’t returned from ajax
  59. Why is a 500 error generated by admin-ajax.php not going into the Apache error log?
  60. Are ‘wp_ajax’ and ‘wp_ajax_nopriv’ exclusive to authenticated and non-authenticated users?
  61. How to HTML5 FormData Ajax
  62. admin-ajax.php vs Custom Page Template for Ajax Requests
  63. How to override WP_DEBUG for Ajax responses?
  64. Stop admin-ajax?
  65. redirect out of wp-admin, without losing admin-ajax.php
  66. Call to undefined function add_action()
  67. Is it safe to assume that a nonce may be validated more than once?
  68. Including WordPress in RESTful API
  69. Multiple ajax nonce requests
  70. Get posts with ajax
  71. admin-ajax.php doesn’t work when using POST data and Axios
  72. How to call a PHP function with Ajax when the user clicks a button
  73. REST API endpoint for elasticpress autosuggest
  74. Ajax for non-logged-in users
  75. Contact Form 7 Custom Post Action
  76. Custom Form with Ajax
  77. How to process ajax requests correctly using ajax plugins
  78. ajax – why multiple calls to wp_create_nonce() return same value?
  79. Update user meta using with ajax
  80. Registering AJAX callback function that is part of a class without instantiating the class in function.php
  81. WordPress function that makes HTML safe to be sent via AJAX request
  82. How do I hook an Ajax request into a PHP callback?
  83. AJAX request on the frontend always returns 0 if user is not admin
  84. admin-ajax.php returns 0. How do I debug it and fix it?
  85. Ajax requests without JQuery
  86. Admin Notification after save_post, when ajax saving in gutenberg
  87. How to properly use wp.ajax.post?
  88. Load tinyMCE / wp_editor() via AJAX [duplicate]
  89. How to tie built in AJAX to an add_action?
  90. Using Nonces for AJAX that only retrieves data
  91. WordPress AJAX Login Screen
  92. AJAX vs Fragment Caching for W3 Total Cache [closed]
  93. Saving (Updating) Post / Page Edits With AJAX
  94. Is there any way of of making an admin-ajax request without the use of die()?
  95. How to verify nonce from Bulk/Quick Edit in save_post?
  96. Using ajax on categories and wordpress loops
  97. Custom PHP endpoint for a plugin’s AJAX call
  98. Detecting post type within init action
  99. Ajax request returning full page code
  100. Basic question on passing variables to AJAX in WordPress
Categories ajax Tags ajax, post-meta, wp-update-post
Creating two tables in database on activation hook
I cannot login and am getting this error message. .

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress