0

How can I update post meta inside the WP_Query? Does this mean inside the loop? Sorry, I'm not too technical about this.

This is the code I'm using:

   <?php
    if(isset($_POST['jolly'])){
    update_post_meta($post->ID , 'carry', 3); 
    }
    ?>
    <form action='' method='POST'>
    <input type='submit' name='jolly' value='test' />
    </form>

Are there alternative ways?

1 Answer 1

1

The Loop is PHP code used by WordPress to display posts. You can see how a loop is constructed on generatewp.com.

// WP_Query arguments
$args = array ();

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while( $query->have_posts() ) {
        $query->the_post();
        $post = get_post();
        if ( isset( $_POST[ 'jolly' ] ) ) {
            update_post_meta( $post->ID, 'jolly', $_POST[ 'jolly' ] );
        }
    }
} else {
    // no posts found
}

// Restore original Post Data
wp_reset_postdata();
?>

<form action='' method='POST'>
    <input type='submit' name='jolly' value='test'/>
</form>
2
  • Should also be noted that you should sanitize & escape any user inputs: codex.wordpress.org/… Commented Nov 13, 2016 at 15:40
  • @megmorsie - absolutely. Omitted here just to show order but sanitization is a must.
    – jgraup
    Commented Nov 13, 2016 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.