WordPress.org

Ready to get started?Download WordPress

Codex

it:Il Loop

Contents

Il Loop è il codice PHP utilizzato da WordPress per visualizzare gli articoli. Utilizzando Il Loop, WordPress processa ciascun articolo per essere visualizzato sulla pagina corrente e lo formatta secondo i criteri specificati tramite i tag de Il Loop. Ogni codice HTML o PHP presente nel Loop verrà eseguito per ciascun articolo.

Quando nelal documentazione di WordPress si legge "questo tag deve essere all'interno de Il Loop", sia per uno specifico Tag dei template o per i plugin, il tag verrà eseguito per ciascun articolo. Ad esempio, Il Loop visualizza di base per ciascuna articolo le seguenti informazioni:

È possibile visualizzare altre informazioni per ciasucn articolo utilizando gli opportuni Tag dei Template o (per gli utenti esperti) accedendo alle variabili di $post, che vengono impostate con le informazioni dell'articolo corrente mentre si esegue Il Loop.

Per chi inizia con Il Loop si veda The Loop in Action.

Utilizzare Il Loop

Il Loop deve essere inserito in index.php ed in ogni altro Template utilizzato per visualizzare informazioni sugli articoli.

Assicurarsi di inserire una chiamata al template della testata all'inizio del vostro template del Tema. Se state utilizzando Il Loop all'interno di un vostro design (ed il vostro design non è un template), impostate WP_USE_THEMES a false:

<?php define('WP_USE_THEMES', false); get_header(); ?>

Il loop inizia qui:

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

e finisce qui:

<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

Questo esempio usa la sintassi alternativa di PHP per le strutture di controllo e può essere scritto anche come:

<?php 
	if ( have_posts() ) {
		while ( have_posts() ) {
			the_post(); 
			//
			// Qui il contenuto dell'articolo
			//
		} // end while
	} // end if
?>

Esempi di Loop

Stilizzare in maniera diversa gli articoli di una categoria

Questo esempio visualizza ciascuna articolo con il proprio Titolo (che viene utilizzato come link all'Articolo - Permalink), le Categorie ed il Contenuto. Inoltre fa si che gli articoli che hanno ID di Categoria '3' vengano stilizzati differentemente. Per far ciò viene utilizzato il Tag dei Template in_category(). Leggete attentamente i commenti per capire cosa faccia ogni parte del codice.

 <!-- Avvio del Loop. -->
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

 <!-- Esegue un test per vedere se l'articolo corrente è nella categoria 3. -->
 <!-- Se lo è, al div che lo contiene viene assegnata la classe CSS "post-cat-three". -->
 <!-- Altrimenti al div che lo contiene viene assegnata la classe CSS "post". -->

 <?php if ( in_category('3') ) { ?>
           <div class="post-cat-three">
 <?php } else { ?>
           <div class="post">
 <?php } ?>


 <!-- Visualizza il Titolo come link al Permalink dell'Articolo. -->

 <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permalink a <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>


 <!-- Visualizza la data (in formato November 16th, 2009 - ndt: la data su un WordPress con impostata la lingua italiana appararirà in formato italiano) ed un link agli altri articoli dello stesso autore. -->

 <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>


 <!-- Visualizza il contenuto dell'Articolo in un div. -->

 <div class="entry">
   <?php the_content(); ?>
 </div>


 <!-- Visualizza un elenco separato da virgolo delle Categorie dell'articolo. -->

 <p class="postmetadata">Pubblicato in <?php the_category(', '); ?></p>
 </div> <!-- Chiude il primo div  -->


 <!-- Ferma Il Loop (ma non il comando "else:" - si veda la riga seguente). -->

 <?php endwhile; else: ?>


 <!-- Viene verificato il primo "if" per vedere se vi sono articoli da -->
 <!-- visualizzare.  Questa parte "else" indica cosa fare se non ve ne sono. -->
 <p>Spiacenti, nessun articolo corrisponde ai criteri di ricerca indicati.</p>


 <!-- Ferma VERAMENTE Il Loop. -->
 <?php endif; ?>

Nota: tutto il codice HTML deve essere all'esterno dei tag <?php  ?>. Ed il codice PHP (anche delle cose semplici come le parentesi graffe: } ) deve stare dentro i tag <?php  ?>. Potete aprire o chiudere blocchi di codice PHP per inserire codice HTML dentro i comandi if ed else come mostrato nell'esempio precedente.

Escludere Articoli di una data Categoria

Questo esempio mostra come nascondere alla visualizzazione una specifica Categoria o alcune Categorie. Inq uesto caso vengono esclusi gli articoli delle Categorie 3 ed 8. L'esempio differisce da quello precedente in quanto modifica la query stessa.

 <?php query_posts($query_string . '&cat=-3,-8'); ?>
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

 <div class="post">
 
 <!-- Visualizza il Titolo come link al Permalink dell'Articolo. -->
 <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permalink a <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

 <!-- Visualizza la data (in formato November 16th, 2009 - ndt: la data su un WordPress con impostata la lingua italiana appararirà in formato italiano) ed un link agli altri articoli dello stesso autore. -->
 <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>
 
  <div class="entry">
    <?php the_content(); ?>
  </div>

  <p class="postmetadata">Pubblicato in <?php the_category(', '); ?></p>
 </div> <!-- Chiude il primo div -->

 <?php endwhile; else: ?>
 <p>Spiacenti, nessun articolo corrisponde ai criteri di ricerca indicati..</p>
 <?php endif; ?>

Nota: Se utilizate questo esempio per la vostra pagina principale dovrete usare un Template diverso per i vostri Archivi di Categoria, altrimenti WordPress escludera gli articoli della Categoria 3 anche quando si sta vedendo il suo archivio di Categoria! Tuttavia se volete usare lo stesso file dei template potete superare il problema usando il tag is_home() per assicurarvi che la Categoria 3 venga esclusa solo dalla pagina principale:

...
<?php if ( is_home() ) {
query_posts($query_string . '&cat=-3');
}
?>
...

Vi sono altri Tag Condizionali che possono venir usati per controllare l'output in funzioni del fatto che una particolare condizione sia vera o falsa rispetto alla pagina richiesta.

Multiple Loops

This section deals with advanced use of The Loop. It's a bit technical – but don’t let that scare you. We’ll start off at easy and work up from there. With a little common sense, patience, and enthusiasm, you too can do multiple loops.

First off, "why would one want to use multiple loops?" In general, the answer is that you might want to do something with one group of posts, and do something different to another group of posts, but display both groups on the same page. Something could mean almost anything; you are only limited by your PHP skill and your imagination.

We will get into examples below, but first you should read about the basics. Take a look at the basic Loop. It consists of:

     <?php if (have_posts()) : ?>
               <?php while (have_posts()) : the_post(); ?>    
               <!-- do stuff ... -->
               <?php endwhile; ?>
     <?php endif; ?>

In English (PHP types and people familiar with code speak can skip to below), the above would be read: If we are going to be displaying posts, then get them, one at a time. For each post in the list, display it according to <!-- do stuff ... -->. When you hit the last post, stop. The do stuff line(s), are template dependent.

A little aside on Do stuff: in this example it is simply a placeholder for a bunch of code that determines how to format and display each post on a page. This code can change depending on how you want your WordPress to look. If you look at the Kubrick theme’s index.php the do stuff section would be everything below:

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

To above:

     <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

An explanation for the coders out there: The have_posts() and the_post() are convenience wrappers around the global $wp_query object, which is where all of the action is. The $wp_query is called in the blog header and fed query arguments coming in through GET and PATH_INFO. The $wp_query takes the arguments and builds and executes a DB query that results in an array of posts. This array is stored in the object and also returned back to the blog header where it is stuffed into the global $posts array (for backward compatibility with old post loops).

Once WordPress has finished loading the blog header and is descending into the template, we arrive at our post Loop. The have_posts() simply calls into $wp_query->have_posts() which checks a loop counter to see if there are any posts left in the post array. And the_post() calls $wp_query->the_post() which advances the loop counter and sets up the global $post variable as well as all of the global post data. Once we have exhausted the loop, have_posts() will return false and we are done.

Loop Examples

Below are three examples of using multiple loops. The key to using multiple loops is that $wp_query can only be called once. In order to get around this it is possible to re-use the query by calling rewind_posts() or by creating a new query object. This is covered in example 1. In example 2, using a variable to store the results of a query is covered. Finally, ‘multiple loops in action’ brings a bunch of ideas together to document one way of using multiple loops to promote posts of a certain category on your blog’s homepage.

Multiple Loops Example 1

In order to loop through the same query a second time, call rewind_posts(). This will reset the loop counter and allow you to do another loop.

  <?php rewind_posts(); ?>
 
  <?php while (have_posts()) : the_post(); ?>
    <!-- Do stuff... -->
  <?php endwhile; ?>

If you are finished with the posts in the original query, and you want to use a different query, you can reuse the $wp_query object by calling query_posts() and then looping back through. The query_posts() will perform a new query, build a new posts array, and reset the loop counter.

  // Get the last 10 posts in the special_cat category.
  <?php query_posts('category_name=special_cat&posts_per_page=10'); ?>

  <?php while (have_posts()) : the_post(); ?>
    <!-- Do special_cat stuff... -->
  <?php endwhile;?>

If you need to keep the original query around, you can create a new query object.

<?php $my_query = new WP_Query('category_name=special_cat&posts_per_page=10'); ?>

<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
  <!-- Do special_cat stuff... -->
<?php endwhile; ?>

The query object my_query is used because you cannot use the global have_posts() and the_post() since they both use $wp_query. Instead, call into your new $my_query object.

Multiple Loops Example 2

Another version of using multiple Loops takes another tack for getting around the inability to use have_posts() and the_post(). To solve this, you need to store the original query in a variable, then re-assign it with the other Loop. This way, you can use all the standard functions that rely on all the globals.

For example:

// going off on my own here
<?php $temp_query = $wp_query; ?>
<!-- Do stuff... -->

<?php query_posts('category_name=special_cat&posts_per_page=10'); ?>

<?php while (have_posts()) : the_post(); ?>
  <!-- Do special_cat stuff... -->
<?php endwhile; ?>

// now back to our regularly scheduled programming
<?php $wp_query = $temp_query; ?>

Note: In PHP 5, objects are referenced with the "= clone" operator instead of "=" like in PHP 4. To make Example 2 work in PHP 5 you need to use the following code:

 // going off on my own here
 <?php $temp_query = clone $wp_query; ?>
 <!-- Do stuff... -->
 
 <?php query_posts('category_name=special_cat&posts_per_page=10'); ?>
 
 <?php while (have_posts()) : the_post(); ?>
   <!-- Do special_cat stuff... -->
 <?php endwhile; ?>
 <?php endif; ?>
 
 // now back to our regularly scheduled programming
 <?php $wp_query = clone $temp_query; ?>

However, this second example does not work in WordPress 2.1.

Multiple Loops in Action

The best way to understand how to use multiple loops is to actually show an example of its use. Perhaps the most common use of multiple loops is to show two (or more) lists of posts on one page. This is often done when a webmaster wants to feature not only the very latest post written, but also posts from a certain category.

Leaving all formatting and CSS issues aside, let us assume we want to have two lists of posts. One which would list the most recent posts (the standard 10 posts most recently added), and another which would contain only one post from the category ‘featured’. Posts in the ‘featured’ category should be shown first, followed by the second listing of posts (the standard). The catch is that no post should appear in both categories.

Step 1. Get only one post from the ‘featured’ category.

  <?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
  while ($my_query->have_posts()) : $my_query->the_post();
  $do_not_duplicate = $post->ID; ?>
    <!-- Do stuff... -->
  <?php endwhile; ?>

In English the above code would read:

Set $my_query equal to the result of querying all posts where the category is named featured and by the way, get me one post only. Also, set the variable $do_not_duplicate equal to the ID number of the single post returned. Recall that the Do stuff line represents all the formatting options associated for the post retrieved.

Note that we will need the value of $do_not_duplicate in the next step to ensure that the same post doesn't appear in both lists.

Step 2. The second loop, get the X latest posts (except one).

The following code gets X recent posts (as defined in WordPress preferences) save the one already displayed from the first loop and displays them according to Do stuff.

  <?php if (have_posts()) : while (have_posts()) : the_post(); 
  if( $post->ID == $do_not_duplicate ) continue;?>
   <!-- Do stuff... -->
  <?php endwhile; endif; ?>

In English the above code would read:

Get all posts, where a post equals $do_not_duplicate then just do nothing (continue), otherwise display all the other the posts according to Do stuff. Also, update the cache so the tagging and keyword plugins play nice. Recall, $do_not_duplicate variable contains the ID of the post already displayed.

The End Result

Here is what the final piece of code looks like without any formatting:

  <?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
  while ($my_query->have_posts()) : $my_query->the_post();
  $do_not_duplicate = $post->ID;?>
    <!-- Do stuff... -->
  <?php endwhile; ?>
    <!-- Do other stuff... -->
  <?php if (have_posts()) : while (have_posts()) : the_post(); 
  if( $post->ID == $do_not_duplicate ) continue; ?>
   <!-- Do stuff... -->
  <?php endwhile; endif; ?>

The end result would be a page with two lists. The first list contains only one post -- the most recent post from the 'feature' category. The second list will contain X recent posts (as defined in WordPress preferences) except the post that is already shown in the first list. So, once the feature post is replaced with a new one, the previous feature will show up in standard post list section below (depending on how many posts you choose to display and on the post frequency). This technique (or similar) has been used by many in conjunction with knowledge of the Template Hierarchy to create a different look for home.php and index.php. See associated resources at the bottom of this page.

Note for Multiple Posts in the First Category

If posts_per_page=2 or more, you will need to alter the code a bit. The variable $do_not_duplicate needs to be changed into an array as opposed to a single value. Otherwise, the first loop will finish and the variable $do_not_duplicate will equal only the id of the latest post. This will result in duplicated posts in the second loop. To fix the problem replace

<?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
 while ($my_query->have_posts()) : $my_query->the_post();
 $do_not_duplicate = $post->ID;?>

with

<?php $my_query = new WP_Query('category_name=featured&posts_per_page=2');
  while ($my_query->have_posts()) : $my_query->the_post();
  $do_not_duplicate[] = $post->ID ?>

Note that "posts_per_page" can be any number. This changes $do_not_duplicate into an array. Then replace

<?php if (have_posts()) : while (have_posts()) : the_post(); if( $post->ID ==
  $do_not_duplicate ) continue; ?>

with

<?php if (have_posts()) : while (have_posts()) : the_post(); 
 if (in_array($post->ID, $do_not_duplicate)) continue;
 ?>

Where you continue the pattern for whatever posts_per_page is set equal to (2 in this case).

Alternatively you can pass the entire $do_not_duplicate array to $wp_query and only entries that match your criteria will be returned:

<?php query_posts(array('post__not_in'=>$do_not_duplicate));
 if (have_posts()) : while (have_posts()) : the_post();
 ?> 

Note that instead a string, the query parameter was an associative array, with post__not_in option.

Nested Loops

Nesting loops means that you are running a second loop before finishing the first one. This can be useful to display a post list with a shortcode for example.

   $my_query = new WP_Query( "cat=3" );
   if ( $my_query->have_posts() ) { 
       while ( $my_query->have_posts() ) { 
           $my_query->the_post();
           the_content();
       }
   }
   wp_reset_postdata();

It is necessary to reset the main loop data after a nested loop so that some global variables hold the correct values again.

Sources

The section on multiple loops is a combination of Ryan Boren and Alex King's discussion about the Loop on the Hackers Mailing List. The nested loops example was inspired by another discussion on the mailing list and a post by Nicolas Kuttler.

Resources

Related

To learn more about the WordPress Loop, and the various template tags that work only within the Loop, here are more resources:

More About The Loop

Articles

Code Documentation

  • Class: WP_Query - Detailed Overview of class WP_Query
  • Object: $wpdb - Overview on the use of the $wpdb object
  • Function: get_query_var()
  • Function: query_posts() - Create additional custom query
  • Function: get_post() - Take an ID of an item and return the records in the database for that article
  • Function: get_posts() - A specialized function that returns an array of items
  • Function: get_pages() - A specialized function that returns an array of pages
  • Function: have posts() - a condition that determines whether the query returned an article
  • Function: the_post() - Used to automatically set the loop after a query
  • Function: rewind_posts() - Clears the current loop
  • Function: setup_postdata() - Sets the data for a single query result within a loop
  • Function: wp_reset_postdata() - Restores the previous query (usually after a loop within another loop)
  • Function: wp_reset_query()
  • Function: is_main_query() - Ensures that the query that is being changed is only the main query
  • Action Hook: pre_get_posts - Change WordPress queries before they are executed
  • Action Hook: the_post - Modify the post object after query
  • Filter Hook: found_posts - Changes the value of the object found_posts WP_Query
This article is marked as in need of editing. You can help Codex by editing it.