WordPress: displaying content outside the Loop

a quick WordPress tutorial

I assume everyone out there know what WordPress is and what it does.

The Loop is the process that occurs when WordPress reads the database and outputs your posts or pages to the destination Html page.
A more detailed explanation can be found here.

Inside the Loop you can use Template Tags (see this page) to modify the output information and choose what elements of the post should be displayed (see Post Tags).

This is the very basic concept behind WordPress templates.

With WordPress you have also the ability to make custom queries to the database to extract your specific content.
In this case, you will need the following sintax:

<?php query_posts('category_name=news&showposts=5'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
 
     <div class="news">          
          <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
          <?php the_excerpt(); ?>          
     </div>
            
<?php endwhile; ?>
<?php endif; ?>

The code above works perfectly when you are inside the Loop, but what if you are outside of it?
Or if you want to include contents from two different loops, for example for making an Asides section?
Then the query_posts() function will not be of any help.

You will have to make a totally new custom query, using a different sintax.
This is needed in order to not overwrite the data retrieved by the main Loop query.

It will look like this:

<?php $my_query = new WP_Query('pagename=another-static-page'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php $do_not_duplicate = $post->ID; ?>
          
      <h1><?php the_title(); ?></h1>
      <?php the_content(); ?>
            
<?php endwhile; ?>

The first line:

<?php $my_query = new WP_Query('pagename=another-static-page'); ?>

makes the new query and storing the retrieved data inside the $my_query variable.
That’s the reason why we have that strange sintax $my_query->have_posts() later on.
This ensures we are browsing data only inside our new variable.

This line:

<?php $do_not_duplicate = $post->ID; ?>

makes sure we’re not duplicating posts, so the same post won’t appear in both queries.

As you can see, then we can output the information with the same good old sintax:

      <?php the_content(); ?>

This way of retrieving and displaying custom information from your WordPress database comes very handy when creating advanced themes or when using WP as a CMS platform and you want to have full control on what is displayed.

As always, the best place to find exhaustive information about Wordpress tweaks is the Codex website.

This tutorial is provided as is. Please do not email me questions or support requests about the scripts contained in this page. Use the comments below instead. Thank you.


About this entry