0

I've got the post id from the meta value and used while loop to show them. Now my problem is that I also need a form to add another meta value (e.g. 1,2,3) for meta key 'rank' to each post id.

$args = array(
              'meta_key' => 'e_id',
              'meta_value' => $eid,
              'post_type' => 'rsvp',
              'post_status' => 'any',
              'posts_per_page' => -1
          );
$the_query = new WP_Query( $args ); ?>

<form action="" method="post"><?
      if ( $the_query->have_posts() ) :
      while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <input type='text' name='rank' ><?   
      endwhile;
      endif;?>
      <input type="submit" name="submitBtn" value="Update"/>
    </form>

Since the form will stay on the same page after submit button is clicked so I did something like this as well, but it did not work as expected.

if(isset($_POST['submitBtn'])){
              add_post_meta($post->ID, 'rank', $_REQUEST['rank'], true);
    }

I really have no idea where to put this and how to make it work with the loop.

Thanks in advance!

  • No Sir, I use it in my custom php. – ThePs Oct 21 '17 at 21:19
1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.