Foreach loop on a wp database query

I’m using WordPress as my favourite cms software. Have worked with different WordPress specific queries like WP_Query, get_posts, query_posts, etc.

My question would be about the programming side. What if I ever will need to use for example a foreach loop inside a specific WordPress query->loop? I guess, sometimes it is not necesary to use wp loop inside another wp loop and it is recommended to use a simple php loop?

Read More

Thanks in advance!

Related posts

Leave a Reply

4 comments

  1. You’re right. There are situations when it is not required to do another database query in an existing loop. In this situations you can use the foreach loop.

    Example:

    $childrens = query_posts('showposts=10&&post_type=post');
    foreach ( $childrens as $children ) {
        // dos tuff here
    }
    

    To see data stored in $children, use print_r():

    print_r( $childrens );
    

    $children->ID is an example of an object property.

    Let me know.

    Edit: More documentations about foreach, here: php-net foreach loops

  2. You can loop inside another loop:

    <?php while(have_posts()): the_post() ?>
    
        <h2><?php the_title() ?></h2>
        <?php
            // preserve global post variable
            global $post; $temp = $post;
            $args = array('posts_per_page'=>3);
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'category',
                    'terms' => array('featured'),
                    'field' => 'slug',
                )
            );
            $new_query = new WP_Query($args);
            while($new_query->have_posts()): $new_query->the_post();
        ?>
        <h3>Featured: <?php the_title() ?></h2>
        <?php endwhile; $post = $temp; wp_reset_query(); ?>
    
    <?php endwhile; ?>
    

    The code above displays 3 latest posts in the category “Featured”.

  3. You don’t need to use foreach, but you can if you choose to.

    The current version of WordPress (3.5 and lower), doesn’t implement interators, but it provides some methods that have the functionality of an iterator.

    For example $query->have_posts() will advance to the next post. But you’ll still need to setup WP globals using $query->the_post() before using functions valid within “the loop“, because those functions rely on global variables

  4. While it’s completely up to you how you structure your pages, there are definitely use cases for inner loops inside of The Loop in WordPress.

    Say you’ve got an index page with a listing of posts, and under each post you want to list “related posts.” You might, for example, loop through your posts and then use WP_Query to foreach through recent posts with the same tags.