07788 994423 · [email protected]

WordPress Loop

The WordPress Loop is the code that displays content on a website. The loop can be used to display blog posts or other types of work depending on what you need it for, and will usually start from the beginning until there are no more entries left.

WordPress’s Loop is a versatile and complex function that you can customize to your needs. The code at the base of this process, though simple in nature, has many hidden complexities for advanced users who want more control over their site content.

Examples of the WordPress Loop 1

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h2><?php the_title() ;?></h2>
	<?php the_post_thumbnail(); ?>
	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, no posts to list</p>

<?php endif; ?>

Examples of the WordPress Loop 2

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h1><?php the_title() ;?></h1>	
	<?php the_content(); ?>

<?php endwhile; else: ?>

	<p>Sorry, this page does not exist</p>

<?php endif; ?>

Examples of the Custom Post WordPress Loop

<?php 
$homepage_post = new WP_Query( array(
  'posts_per_page' => 3,
  'post_type' => 'my-custom-post'
));

while ($homepage_post->have_posts()) {
$homepage_post->the_post(); ?>

<a href="<?php the_permalink(); ?>"><h2>  <?php the_title(); ?> </h2></a>  
<?php } wp_reset_postdata();
?>

Examples of the Custom Post WordPress Loop 1

<?php
$homepageEvents = new WP_Query(array(
  'posts_per_page' => 2,
  'post_type' => 'my-custom-post'
));

while($homepageEvents->have_posts()) {
  $homepageEvents->the_post(); ?>
  <div class="event-summary">
    <a class="event-summary_date" href="#">
      <span class="event-summary_month">Mar</span>
      <span class="event-summary_day">25</span>
    </a>
    <div class="event-summary_content">
      <h5 class="event-summary_title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
      <p><?php echo wp_trim_words(get_the_content(), 18); ?> <a href="<?php the_permalink(); ?>" >Learn more</a></p>
    </div>
  </div>
<?php }
?>

Examples of the Custom Post WordPress Loop 2

<?php
$homepagePost = new WP_Query(array(
  'posts_per_page' => 2,
  'post_type' => 'my-custom-post'
));
?>
<?php if ( $homepagePost->have_posts() ) : while ( $homepagePost->have_posts() ) : $homepagePost->the_post(); ?>

  <h1><?php the_title() ;?></h1>      
  <?php echo wp_trim_words ( get_the_content(), 10); ?>

<?php endwhile; else: ?>

  <p>Sorry, there are no posts to display</p>

<?php endif; ?>

You can find out more about working with the WP_Query on the WordPress Codex.

The WordPress loop is the backbone of all dynamic sites built on WordPress. You can’t just use it, but you must also customize it by tailoring your content to fit your needs. There are tons and tons of functions that allow for customization like conditional tags or WP_Query if you need more advanced functionality.