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

delete post meta by AJAX

Your problem is global $post.

You have to understand that any ajax call, is a new http request, that has nothing to do with the page that send the ajax request.

If you want to pass information from the page that send the request to the page that receive the request, you have to pass the data inside the data argument in jQuery.ajax function.

Note that the function that print the shortcode receive the current post object as argumnet, so you can make use of it:

function testdel( $post ) { // note the $post varaible as argument
  wp_nonce_field('testdel', 'ajaxsecurity'); // is a good practise adding nonces
?>
  <input type="hidden" value="<?php echo $post->ID; ?>" id="ajaxtestdel_postid">
  <tr>
    <th scope="row"><label for="del">delete test key</label></th>
    <td><input type="button" name="del" id="del" value="delete" class="button"></td>
  </tr>
  <script>
  jQuery('#del').on('click', function(){
    var $this = jQuery(this);
    var post = jQuery('#ajaxtestdel_postid').val(); // get post id from hidded field
    var nonce = jQuery('input[name="ajaxsecurity"]').val(); // get nonce from hidded field
    jQuery.ajax({
      url: ajax_url, // in backend you should pass the ajax url using this variable
      type: 'POST',
      data: { action : 'ajaxtestdel', postid: post, ajaxsecurity: nonce },
      success: function(data){
        console.log(data);
        $this.val('deleted');
      }
    });
  });
 </script>
 <?php
}

Now the ajax function:

function ajaxtestdel() {
  $postid = isset($_POST['postid']) ? $_POST['postid'] : '';
  $nonce = isset($_POST['ajaxsecurity']) ? $_POST['ajaxsecurity'] : '';
  if ( $postid && $nonce && wp_verify_nonce($nonce, 'testdel') ) {
    $status = delete_post_meta($postid, 'test') ? 'Error' : 'Success';
  } else {
     $status="Error";
  }
  die($status);
}

add_action('wp_ajax_ajaxtestdel', 'ajaxtestdel');

Also note that is a good practise separate js from php, so your js should go in a separate js file, enqueued in the post edit page using admin_enqueue_script hook and wp_enqueue_script function.

Related Posts:

  1. Using WP_Query to grab custom meta values, foreach to json object
  2. Collect custom post in a calendar
  3. WordPress AJAX load post metadata in modal
  4. JSON parsing error syntax error unexpected end of input
  5. Pass request headers in a jQuery AJAX GET call
  6. jQuery Ajax error handling, show custom exception messages
  7. How to send multiple data fields via Ajax?
  8. My javascript is returning this error: $.ajax is not a function
  9. Jquery Ajax Posting JSON to webservice
  10. Ajax TypeError: $.POST is not a function
  11. TypeError: $.ajax(…) is not a function?
  12. XML Parsing Error: not well-formed in FireFox but good in Chrome
  13. Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
  14. How to fix the ‘Missing required request header. Must specify one of: origin,x-requested-with’ Ajax Error
  15. What’s the point of the X-Requested-With header?
  16. How to get a cross-origin resource sharing (CORS) post request working
  17. jQuery Form Validation before Ajax submit
  18. jQuery – Illegal invocation
  19. jQuery ajax error function
  20. How to manage ajax calls and JSON in wordpress
  21. ajax stopped working when not logged in?
  22. Using jQuery to delete data stored in wp_options
  23. post formats – how to switch meta boxes when changing format?
  24. WordPress AJAX File Upload – FrontEnd
  25. How to add a ” waiting” icon for an ajax in WP frontend?
  26. Can’t get a JSON object in response to an Ajax request with wp_ajax
  27. What is the simplest ajax upload plugin or script to be used with wordpress?
  28. AJAX nonce with check_ajax_referer()
  29. Creating Ajax backend for Specialised Page Template? Should admin-ajax.php be used?
  30. WordPress Ajax URL for function in functions.php
  31. Infinite scroll / lazy loading with NextGen Gallery [closed]
  32. wp_mail script with jQuery post
  33. Ajax call does not activate callback function
  34. AJAX call returns 0
  35. AJAX function returning -1
  36. call shortcode in javascript
  37. WP set auth cookie using Ajax is not saved to browser
  38. jQuery and AJAX Not working with Select Form Element
  39. WordPress: Sortable Metabox Fields Not Saving Position
  40. How to reload a select box of posts dynamically?
  41. How to pass both action and formdata in wordpress ajax?
  42. jquery & ajax getting data to php in wordpress
  43. AJAX returns response 0
  44. jQuery AJAX form validation
  45. Media manager multiple selection
  46. Passing a varible from jQuery to PHP
  47. Proper way to load a single post via Ajax?
  48. Basic WordPress AJAX Call
  49. Add X meta box inputs based on form at top of meta box, how to do it right?
  50. Unbind postbox click handler
  51. Trying to get single posts to load on the front page via ajax
  52. ajax call in wordpress front end
  53. AJAX post into pop-up div
  54. Bind to WPSetAsThumbnail
  55. Ajax not firing properly using Firefox, but works in Chrome
  56. Disable collapse of admin meta boxes
  57. jQuery Ajax() doesn’t work when the page is accessed as a WordPress template page
  58. Script dependencies for post.js
  59. Appending anchor tag to next post
  60. How to Use JSON With AJAX?
  61. wp_localize_script, variable is not defined in jquery
  62. How to load whole WordPress pages dynamically with AJAX/jQuery like this following website?
  63. Using wp_ajax and wp_ajax_nopriv hooks
  64. WP REST return value to error function from Request
  65. Creating custom AJAX requests
  66. How to pass jQuery ajax URL value
  67. Registration e-mail check with AJAX
  68. Cannot access elements of json object
  69. Basic ajax call in WordPress
  70. Updating User Profile with AJAX not working
  71. how to get the comment ID in the front end when the REPLY button is clicked?
  72. validate a metabox based on the category that is selected
  73. Auto Load New Posts
  74. Admin wp_ajax hook returning 0
  75. Edit single attachment on click (WP-admin)
  76. wp_ajax() question.. not using wp_enqueue_script?
  77. wp_ajax unauthenticated and authenticated
  78. Showing Author Information and Latest Post by author in lightbox when clicked on the name of the author
  79. WordPress ajax function parameter value not being passed
  80. WordPress Ajax not function as I expect… what’s wrong?
  81. Trigger JS in custom meta box if a featured image is loaded/exists
  82. Accept AJAX call with serialized form data
  83. wp_verify_nonce not working
  84. Tags in WordPress 3.2
  85. php ajax problem – weird 301 responses!
  86. WordPress customizer refresh screen after save
  87. Is there a restriction in WP on the use of jQuery load function?
  88. Loading posts via AJAX in a hidden div with updated URL?
  89. How to get a value from PHP in Jquery through Ajax
  90. Not sure why wp_ajax isn’t working?
  91. Load created php file data via ajax
  92. Jquery not showing in homepage
  93. Ajax not posting form data to query in PHP function
  94. jQuery Ajax returning correct Response, but after redirect to 404 Error
  95. WordPress Ajax problem with undefined url
  96. How to get those data using with ajax json?
  97. Front-end Ajax File Upload
  98. Correct way to write jQuery functions in WordPress
  99. Display data on same page as form without refresh
  100. Hide metabox dependant on page template chosen
Categories jQuery Tags ajax, jquery, metabox, post-meta
When taxes are country specific they don’t show in the cart totals
Why doesn’t the WYSIWYG support H1-H6 tags?

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
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 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