Hi Backend Developer
WordPress Loop Example for Starters
The WordPress Loop is the code that WordPress uses to display posts. It’s a PHP code block that cycles through the content you have in your database, typically used on archive pages or blog listings.
Basic Structure of the WordPress Loop
Here’s the most basic version of the WordPress Loop that you will find in WordPress themes:
<?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <!-- Start of individual post -->
<h2><?php the_title(); ?></h2> <div><?php the_content(); ?></div>
<!-- End of individual post --> <?php endwhile; ?><?php else : ?> <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p><?php endif; ?>
WordPress Loop with Custom Query Example for Starters
In WordPress, you can create custom queries using the WP_Query
class. This allows you to retrieve posts or custom post types based on specific criteria, such as category, tag, post type, or even custom fields.
Basic Structure of a Custom Query
Here’s a simple example of a WordPress custom query using WP_Query
with some common arguments:
<?php// Custom query arguments$args = array( 'post_type' => 'post', // Get posts (can also be custom post type) 'posts_per_page' => 5, // Limit to 5 posts 'orderby' => 'date', // Order by date 'order' => 'DESC', // Order from newest to oldest);
// The custom query$custom_query = new WP_Query( $args );
// The Loopif ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <!-- Start of individual post -->
<h2><?php the_title(); ?></h2> <p>Published on: <?php echo get_the_date(); ?></p> <div><?php the_excerpt(); ?></div> <!-- Displaying excerpt instead of full content -->
<!-- End of individual post --> <?php endwhile; wp_reset_postdata(); // Always reset post data after custom queryelse : ?> <p><?php esc_html_e( 'No posts found.', 'text-domain' ); ?></p><?php endif; ?>