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 add post meta in while loop?

You should use init action hook. From the codex: init is useful for intercepting $_GET or $_POST triggers.

The following code is just a sample and is untested:

function wpse283607_handle_submit()
{
    // check if form is POSTed and nonce is valid
    if ( 'POST' === $_SERVER['REQUEST_METHOD']
         && wp_verify_nonce( $_REQUEST['_wpnonce'], 'my-action' ) ) {
        if ( !empty( $_REQUEST['rank'] ) ) {
            $ranks = (array) $_REQUEST['rank'];
            foreach ( $ranks as $post_id => $rank ) {
                add_post_meta( intval( $post_id ), 'rank', intval( $rank ) );
            }
        }

        // redirect to the same page (to avoid re-submit form data on browser reload/refresh)
        wp_safe_redirect(
            remove_query_arg( [ '_wp_http_referer', '_wpnonce' ], wp_unslash( $_SERVER['REQUEST_URI'] ) )
        );
        exit;
    }
}

add_action( 'init', 'wpse283607_handle_submit' );

Then your <form> would look something like:

<form action="" method="post"><?
    wp_nonce_field( 'my-action' );
    /**
     * @var \WP_Query $the_query
     */
    if ( $the_query->have_posts() ) :
        $i = 1; // not sure how you generate your "rank" but just an example
        while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <input type="text" name="rank[<?php echo $post->ID ?>]" value="<?php echo $i ?>" /><?
        $i++;
        endwhile;
        wp_reset_postdata();
    endif; ?>
    <input type="submit" name="submitBtn" value="Update" />
</form>

Related Posts:

  1. add_filter the_content str_replace after shortcode
  2. Two posts in same div – WP loop
  3. Upload Image in a WordPress page using PHP
  4. ACF page while loop breaks footer while loop
  5. how to remove metadata from the posts of my blog?
  6. My form action url is being prepended with a directory that does not exists
  7. How to store data from multiple forms using ajax and php
  8. Why Won’t My Inputs in a form with a Get method work together?
  9. Input data from email form not going to JSON file
  10. How to get the value of input hidden html from text editor to custom page template?
  11. Login to wordpress by clicking a link and specifying usernaname and password in url
  12. Get post id within comments loop
  13. Syntax error when I try to insert my loop into an unordered list? [closed]
  14. Search WordPress using static html page
  15. How to execute html code inside php?
  16. WordPress loop by meta key that is an array? and how loop multiple arrays
  17. Calling function in loop causes repeat data
  18. Adding attribute to the post.php form tag in wp-admin
  19. Front end file upload returning wrong attachment url
  20. WordPressUser Submission Form
  21. Custom forms with HTML
  22. Search AJAX Filters – Multiple Query Loops Into One Loop (Optimization)
  23. Cascading dropdown select search based on Parent Page & Child Page
  24. HTML Form Question
  25. How can I get my pagination loop to display the correct number of total pages?
  26. wordpress form action page not found
  27. Custom HTML form using PHP – help with ajax/username validation
  28. how to remove replicating a tag inside loop?
  29. Efficient way of querying for a “fallback” post?
  30. Post from front end form to post_meta
  31. Automatically create a loop for post ID
  32. What is the best way to get the first few post from WordPress in different divs using a loop?
  33. get_post_meta is always empty when I use wp_mail
  34. Implement “No related posts for this entry” into the loop?
  35. Saving meta box data from selected option’s value in database is not working
  36. How to modify default tags in wp_head()
  37. How to show correct td of table tags in wp_query loop
  38. How can I process a form submission from an HTTP POST request?
  39. How do I let users upload files to a chosen location?
  40. Missing sidebar parameter “fix” – before_content
  41. woocommerce registration form with klaviyo(don’t work with current user)
  42. Use object in template part
  43. How Display Posts on category
  44. How to get the POST TITLE using the POST ID?
  45. Get Current User Id Inside a Loop Returns 0 For a Shortcode
  46. HTML tags in bloginfo description
  47. Get first URL from post content
  48. Random order of WP_Query results with highest meta value
  49. How can I add multiple ‘tax_query’ arrays via a loop?
  50. Getting a specific post values to another div or modal
  51. Add a class to the anchor tag on HTML5 gallery
  52. Transferring working local PHP site to wordpress – with database (MySQL)
  53. Using foreach loop breaks
  54. Cannot display or echo alt text on featured image
  55. The text box have space character
  56. Using Advanced Custom Fields to create a per page slider
  57. Split loop into two columns, how to favor one side over the other
  58. How can I create a list of page titles from custom meta values?
  59. Load a page into a div with Ajax
  60. WordPress Search Results for Multiple Post Types
  61. Trying to remove post thumbnail with plugin
  62. How to create a form and display its content as table in admin panel?
  63. Randomly Assign an Image’s Alt Text Based on Data From Post
  64. Custom Form Processing Issue
  65. Where in PHP do I move title and meta (date) to bottom of each blog section?
  66. Changing layout with wp_customise
  67. Advanced Meta Query for Large Calendar Website (12k+ posts) (175k+ wp_postmeta rows)
  68. Converting HTML Template to WordPress Theme
  69. Multiple options not staying selected after saving
  70. Dynamic Stylesheet loads but doesn’t finish
  71. Custom profile field with birthday. Troubles with
  72. Filter Select results based on selection
  73. Using loop pagination on single.php
  74. Using the echo command adds unwanted br tags to source
  75. custom fields wordpress
  76. Loop with slider (slider not loading)
  77. How to hide all child pages with post_query?
  78. Why the JavaScript code is ignored from wp editor?
  79. How to sort posts based on the value (number) of a post’s metadata?
  80. Show css depending on activity type in BuddyPress activity-loop [closed]
  81. How can I reuse the code to capture a param in a URL and place in a value in a hidden form?
  82. Populate dropdown with Child Pages based on Parent Page chosen
  83. WooCommerce/WordPress: how hide entire table form after submit (Admin Dashboard)?
  84. How to use $query->set with post__in?
  85. search and replace preword from author
  86. Embed html in php code
  87. Why my filterable portfolio page work not perfectly between slug button and slug output WORDRPESS?
  88. Ajax loaded form replaces form action with Ajax url
  89. prevent default not stopping page refresh. Passing form information to and from php with ajax in a wordpress site
  90. Sort custom meta column by other meta value
  91. How to limit the number of forgot password reset attempts in WordPress?
  92. Custom search results page not working with empty search
  93. WP grandchild categories in nested ul li
  94. Modify HTML structure of fields in woocommerce checkout form
  95. Store multiple custom field as post meta per post(css, js, html, 2 link) [closed]
  96. Use DOMDocument with ob_start breaks my HTML code
  97. How to VAR_DUMP a $variable during checkout process (Is my product meta callable?)
  98. Creating user status mode in WordPress
  99. Need help with Google drive API [closed]
  100. Iterate through posts based on array of categories
Categories PHP Tags forms, html, loop, php, post-meta
Insert Address fields into function
Custom taxonomy template shows 404 Error

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