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?
Thanks in advance!
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:
To see data stored in
$children
, useprint_r()
:$children->ID
is an example of an object property.Let me know.
Edit: More documentations about
foreach
, here: php-net foreach loopsYou can loop inside another loop:
The code above displays 3 latest posts in the category “Featured”.
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 variablesWhile 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
toforeach
through recent posts with the same tags.