最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Do I need to use wp_reset_postdata for my function?

matteradmin11PV0评论

I am using this function which seems to work fine, however I was wondering if I must use wp_reset_postdata after endwhile?

function evecal_task_function() {
$args=array(
  'posts_per_page' => -1,
  'post_type' => 'events'
);
$now = time();
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
  while ( $the_query->have_posts() ) : $the_query->the_post();
  $fxdate = strtotime(get_field('fl_date',false,false));$datediff = $now - $fxdate;
    if ( $datediff > 1) {update_field('fl_expire', '1', get_the_ID());}  
  endwhile;
endif;
}

I am using this function which seems to work fine, however I was wondering if I must use wp_reset_postdata after endwhile?

function evecal_task_function() {
$args=array(
  'posts_per_page' => -1,
  'post_type' => 'events'
);
$now = time();
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
  while ( $the_query->have_posts() ) : $the_query->the_post();
  $fxdate = strtotime(get_field('fl_date',false,false));$datediff = $now - $fxdate;
    if ( $datediff > 1) {update_field('fl_expire', '1', get_the_ID());}  
  endwhile;
endif;
}
Share Improve this question asked Oct 23, 2018 at 10:38 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Yes you should, otherwise you could interfere with another query happening on the same page.

Using $the_query->the_post(); interferes with the global $post variable, and wp_reset_postdata() serves that exact purpose, to reset the global $post variable to the original (global) query. Read more

Post a comment

comment list (0)

  1. No comments so far