简体   繁体   中英

Why do we use two different loops to create multiple and static wp-query loops?

Why do we use two different loops to create multiple and static wp-query loops?

1_to modify loops & create multiple loops

<?php $the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>
  <?php while ( $the_query->have_posts() ) : ?>

    <?php $the_query->the_post(); ?>

  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>

2_to create static loop

<?php $custom_posts = get_posts( $args ); ?>

<?php if ( $custom_posts ) : ?>  
  <?php foreach ( $custom_posts as $post ) : ?>

    <?php setup_postdata( $post ); ?>

  <?php endforeach; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>

This is not easy to understand (and also not to explain) from the outside because of side-effects (and what not).

The first example is making use of these as $the_query->the_post() pushes the current post of the query into the global state (invisible in your code) and moves $the_query to the next element (or the ending terminator).

On the other hand the second example works differently: get_posts( $args ) returns an array that is then iterated over with foreach and each array value - the $post - then needs to be "set-up": again the global state is modified, to create the wanted side-effect, now by setup_postdata( $post ); .


Why do we use two different loops to create multiple and static wp-query loops?

Because uncle Matt. There might have been a distraction during important Instagram shootings that prevented the common "Code is poetry" mantra to fully expose its beauty and you just found that historic glitch in the matrix.

Or a clone of Dolly said "hello" and that was part of the confusion as sheep normally don't speak.

The honest truth is, that we can't say here on Stackoverflow, but only the original author(s) if they are willing to remember.

If you can share the actual Wordpress version and the files and the lines of code, it would be possible to at least give reference to the history of these (which can sometimes reveal a rationale if documented with the code). Question remains if it would be really worth to dig deeper on that one.

I suggest to study https://php.net/foreach for more insights as that one is most often the best first utility for loops. Don't take Wordpress code too seriously, there are better examples (there actually was a time where there was no foreach in PHP and the first example is likely originating from that time - maybe 15 years ago or so.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM