Consider this WordPress Loop code snippet inside a template file:
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title();
}
} else {
echo 'No posts found';
}What will this code output if there are 3 published posts?
if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } else { echo 'No posts found'; }
Remember that have_posts() checks if there are posts left, and the_post() moves the pointer to the next post.
The loop runs while have_posts() returns true. Each time the_post() is called, it sets up the current post data. Then the_title() prints the title of that post. So all 3 post titles print one after another.
You want to create a custom query that fetches posts only from category with ID 5. Which argument array is correct?
Check the official WP_Query parameters for category filtering.
The correct parameter to filter by category ID is cat. The others are invalid or expect different values.
Look at this code snippet:
$args = [
'post_type' => 'post',
'posts_per_page' => 5
];
$query = new WP_Query($args);
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title();
}
} else {
echo 'No posts found';
}Why does it show 'No posts found' even if posts exist?
$args = [ 'post_type' => 'post', 'posts_per_page' => 5 ]; $query = new WP_Query($args); if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } else { echo 'No posts found'; }
Think about which loop functions belong to the main query and which belong to a custom query.
The functions have_posts() and the_post() without a query object refer to the main query. To use the custom query, you must call $query->have_posts() and $query->the_post(). Otherwise, the main loop runs and finds no posts.
Given this code snippet inside a template:
$post_count = 0;
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$post_count++;
}
}
echo $post_count;If there are 7 posts in the main query, what will be printed?
$post_count = 0; if ( have_posts() ) { while ( have_posts() ) { the_post(); $post_count++; } } echo $post_count;
Count how many times the loop runs if there are 7 posts.
The loop runs once for each post. Each time it increments $post_count by 1. So after 7 posts, $post_count is 7.
Choose the correct statement about how The Loop and WP_Query interact in WordPress.
Think about how WordPress separates the main query from custom queries.
The main query uses global functions like have_posts() and the_post(). Custom queries require calling methods on the WP_Query object, like $query->have_posts() and $query->the_post(). The other statements are false.