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

How to create a button click counter meta box?

First of all output your javascript in like this is a worse practice. So it’s a lot better if you create your javascript file and the enqueue it using wp_enqueue_script hooked admin_enqueue_scripts action.

function enqueue_my_ajax( $hook ) {
    if( 'post.php' != $hook && 'post-new.php' != $hook ) return;
    // if you use in theme use get_template_directori_uri to retrieve the url
    wp_enqueue_script( 'my_ajax_script', plugins_url('/my_ajax_script.js', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'enqueue_my_ajax' );

Second, when you use metabox and ajax is always a good idea use nonces. You can use wp_nonce_field to create an hidden nonce input in the metabox and the retrieve the value and post with ajax.

Check in Codex for the functions named above for more info.

Regarding the problem, the post Id should be passed via ajax, or ajaxResponse cannot make use of it.

So the function that display your metabox should be:

function wpse_54822_inner_custom_box( $post ) {
  $current_count = get_post_meta($post->ID, '_increment_key', true) ? : 1;
  wp_nonce_field( 'increment_my_count', '_nonce_count' );
?>

<input type="hidden" id="_count" name="_count" value="<?php echo $current_count ? : 1; ?>" />
<input type="hidden" id="_postid" name="_postid" value="<?php echo $post->ID; ?>" />
<div id="counter"><?php printf( 'Current Count: %d', $current_count ); ?></div>
<input type="button" name="button" class="button button-primary submitmeplease" value="<?php _e('Update'); ?>" />

<?php } ?>

Your javascript (in the my_ajax_script.js file enqueued as above) should be:

jQuery(document).ready(function($){
  $('.submitmeplease').on('click', function(e){
    e.preventDefault();
    var nonce = $('input[name="_nonce_count"]').val();
    var count = $('#_count').val();
    var id = $('#_postid').val();
    $.ajax({
      url: ajaxurl,
      type: 'POST',
      data: { _nonce_count: nonce, action: 'update_my_count', _count: count, postid: id },
      success: function( data ) {
        if (data != '' && data != '0')
          $('#_count').val( data );
          $('#counter').html('Current Count: ' + data)
        }
    });
  });
});

Your myUpdateCount function shoud be:

function myUpdateCount() {
  if ( ! check_admin_referer( 'increment_my_count', '_nonce_count' ) ) die();
  $postid = isset( $_POST['postid'] ) && $_POST['postid'] ? $_POST['postid'] : null;
  if ( ! $postid ) die();
  if ( ! current_user_can('edit_posts', $postid) ) die();
  $new_count = isset( $_POST['_count'] ) && $_POST['_count'] ? $_POST['_count'] + 1 : 1;
  update_post_meta($postid, '_increment_key', $new_count);
  die( (string)$new_count );
}

add_action('wp_ajax_update_my_count', 'myUpdateCount');

Related Posts:

  1. Passing error/warning messages from a meta box to “admin_notices”
  2. Add “upload media” button in meta box field
  3. post formats – how to switch meta boxes when changing format?
  4. get registered metaboxes by post type or post ID
  5. How to get meta box data to display on a page
  6. esc before saving or before displaying does it matter?
  7. Access the environment of an admin page from another admin page
  8. Add a meta description to home page?
  9. Why can’t I hook into save_posts after admin_init?
  10. Check if meta key value already exists
  11. get_post_meta doesn’t work
  12. Metabox of one post influence setting on other
  13. Custom Metabox with Ajax in Edit Post – Stuck
  14. How to store multiple input values with same meta_key
  15. Consolidate Metaboxes into 1 Big Metabox
  16. unable to save post meta on single field with multiple selects
  17. metabox upload file
  18. Why is variable value emptry in $_POST but available in $_REQUEST?
  19. Why does get_post_meta not work with the posts page?
  20. Trigger JS in custom meta box if a featured image is loaded/exists
  21. How to get meta box values – WP tuts tutorial
  22. Change the post date from a meta box
  23. update_post_meta and get_post_meta not working
  24. Repeatable custom meta fields
  25. how to save multiple checkboxes value in wordpress dynamically
  26. Using WYSIWYG In custom meta boxes
  27. Multiplicate entry on update_post_meta
  28. Undefined index error in custom post metabox
  29. Custom Meta box only returns most recent value on page
  30. How to prevent further updates of custom meta when using actions to set one meta based on another
  31. meta box & callback function
  32. delete post meta by AJAX
  33. $_GET & $post_ID
  34. get_post_meta as a list for drop down search filter
  35. Parse a text area custom meta box and assign as value to existing meta keys
  36. Getting metabox value?
  37. Hide Page Title with Post Meta
  38. Save meta data with post, Without using any plugin [closed]
  39. Editor meta box Showing but not saving
  40. How can i get multi checkboxes value in metbox?
  41. Show value of select dropdown in meta box
  42. remove a single post_meta
  43. Echo 2 values from one key in Array with get_post_custom
  44. Custom loop attached to link
  45. save radio button selection in post-meta on submit
  46. post meta – problem : copy the same meta for all the articles
  47. Custom Meta Data is not being saved
  48. Update Post Meta in Front End with a form
  49. Update Post meta with custom variable
  50. get_post_meta not working on my custom-function page
  51. update_post_meta doesn’t work
  52. delete post meta data in array WordPress
  53. Collect custom post in a calendar
  54. WordPress AJAX load post metadata in modal
  55. Removing Meta Generator
  56. Only allow one meta key value per post in a category
  57. use post meta in add_meta_boxes action
  58. Custom meta box not saving values of radio buttons in WordPress
  59. Can’t save drop down select date in meta boxes
  60. update_post_meta does not work
  61. add_post_meta not saved
  62. when saveing $meta_box i get Undefined index error
  63. Updating post meta and Meta Box plugin
  64. Related posts and custom meta_box?
  65. Reload meta box content with AJAX
  66. Select Options Meta Data is Not Updating in Edit Meta Box
  67. How to display meta box data using “Meta boxes as needed”
  68. Metadata in loops
  69. Allow iframe in custom meta box
  70. Calling Data from Custom Meta Box
  71. How can i remove blank area caused by theme’s post meta boxes?
  72. Datepicker altField and altFormat to save a new meta key/value in a post?
  73. My meta box don’t want to save value
  74. CPT posts in drop downed in meta box on page doesn’t return post ID
  75. Create more Meta Boxes as needed
  76. Set Default Admin Screen options & Metabox Order
  77. How to set default screen options?
  78. Add a Meta Box for uploading a SECOND Featured Image?
  79. Does WordPress have a “Form API”?
  80. Metabox with checkbox is not updating
  81. How to HIDE everything in PUBLISH metabox except Move to Trash & PUBLISH button
  82. What is the “Advanced” $context in add_meta_box?
  83. Removing panels (meta boxes) in the Block Editor
  84. Change The Title Of a Meta Box
  85. What is the index [0] for on post meta fields?
  86. WordPress SEO by Yoast: Hide Meta Boxes in Posts for Non-admins
  87. How to make open/closed and hidden/shown metaboxes status saved on a per-post basis?
  88. How To Remove The “+ Add New Category” Link From A Category Metabox
  89. How can I create a taxonomy meta-box with search suggestions but no new terms input?
  90. Remove the Featured Image Meta Box
  91. Remove the Yoast SEO Post Metabox [closed]
  92. Best practices for meta box placement?
  93. Creating a metabox to upload multiple images
  94. How Does WordPress Remember Metabox Positions?
  95. Sample code for validating custom metabox?
  96. Post custom metabox textarea using wp_editor
  97. How to Add Reminders/Notes to New Post Meta Boxes
  98. How do I get attachment_id?
  99. Removing Metabox for “Slug” without removing functionality
  100. How to reorder meta box position?
Categories metabox Tags ajax, metabox, post-meta
How to update to WordPress 3.6 and not lose my website’s design
Single.php – Get Current Parent Category

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