2012-12-30

Style Posts From Some Category Differently:

New page

{{Languages|

{{en|The Loop}}

{{it|Il Loop}}

{{ja|The Loop}}

{{pt-br|O Loop}}

{{ru|Цикл WordPress}}

{{zh-cn|循环}}

{{zh-tw|迴圈}}

}}

__TOC__

'''Il Loop''' è il codice PHP utilizzato da WordPress per visualizzare gli articoli. Utilizzando Il The Loop, WordPress processa ciascun articolo da visualizzare sulla pagina corrente e lo compone in accordo ai criteri specificati dai tag de Il Loop tags. Qualsiasi codice [[Glossary#HTML|HTML]] o [[Glossary#PHP|PHP]] presente nel Loop verrà eseguito per ciascun articolo.

Quando a documentazione di WordPress indica "Questo tag deve essere utilizzato all'interno del Loop", come ad esempio degli specifici [[Template Tags|Tag dei template]] oppure dei plugin, il tag verrà ripetuto per ciascun articolo. Ad esempio il Loop visualizza di base, per ciascun articolo, le seguenti informazioni:

* Titolo ([[Template Tags/the_title|the_title()]])

* Data/ora ([[Template Tags/the_time|the_time()]])

* Categorie ([[Template Tags/the_category|the_category()]]).

Altre informazioni riguardanti ciascun articolo possono venir visualizzate utilizzando gli appropriati [[Template Tags | Tag dei template]] oppure (per gli utenti avanzati) accedendo direttamente alla variabile $post, che viene impostata con le informazioni sull'articolo corrente mente Il Loop è in esecuzione.

Per una guida introduttiva a Il Loop si veda [[The Loop in Action]].

== Utilizzo de Il Loop ==

Il Loop deve essere inserito nella index.php ed in qualsiasi altro Template utilizzato per mostrare inforzioni sugli articoli.

Assicurarsi di includere la chiamata al template della testata nei propri templati del [[Theme Development|Tema]]. Se si sta utilizando Il Loop all'interno di un proprio design (ed il design non è un template), impostare WP_USE_THEMES a false:

Il Loop inizia qui:

e finisce qui:

<p>
</p>

== Esempi di Loop ==

=== Applicare uno stile differente agli articoli di determinate categorie ===

Questo esempio visualizza ciascun articolo col suo Titolo (che è utilizato come un link al [[Using Permalinks|Permalink]]) dell'articolo, le categorie ed il contenuto. Inoltre fa si che gli articoli che hanno la categoria di ID '3' abbiano uno stile differente. Per ottenere ciò viene utilizzato il [[Template Tags|Tag dei template]] [[Function Reference/in_category|in_category()]]. Si leggano attentamente i commenti per capire ciò che fa ogni parte del codice.

" rel="bookmark" title="Link permanente a
">

di

Pubblicato in

Termina Il Loop (ma si noti l'"else:" - si veda la riga successiva). -->

Spiacente, nessun articolo corrisponde ai criteri di ricerca.

'''Nota:''' Tutto il codice [[Glossary#HTML|HTML]] deve essere esterno ai tag
. Il codice [[Glossary#PHP|PHP]] (anche una semplice parentesi graffa: } ) deve essere ''dentro'' i tag
. Ancora: il codice PHP deve essere dentro i tag PHP; l'HTML deve essere esterno ad essi. È possibile avviare ed interrompere il codice PHP per inframmezzare codice HTML anche fra comandi if e else come mostrato nell'esempio precedente.

=== Exclude Posts From Some Category ===

This example can be used to exclude a certain Category or Categories from being displayed. In this case, posts from Categories 3 and 8 are excluded. The example is different than the [[#Style Posts From Some Category Differently|example above]] in that it makes a change to the [[Template_Tags/query_posts|query]] itself.

" rel="bookmark" title="Permanent Link to
">

by

Posted in

Sorry, no posts matched your criteria.

'''Note''': If you use this example for your main page, you should use a different [[Templates|Template]] for your [[Category Templates|Category archives]], otherwise, WordPress will exclude all posts in Category 3, even when viewing that Category Archive! However, if you want to use the same template file, you can avoid this by using the [[Function_Reference/is_home|is_home()]] tag to ensure posts from Category 3 will only be excluded from the main page:

...

...

There are other [[Conditional Tags]] that can be used to control the output depending on whether or not a particular condition is true with respect to the requested page.

==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:

<!-- do stuff ... -->

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:

To above:

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.

<!-- Do stuff... -->

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.

<!-- Do special_cat stuff... -->

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

have_posts()) : $my_query->the_post(); ?>

<!-- Do special_cat stuff... -->

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

<!-- Do stuff... -->

<!-- Do special_cat stuff... -->

// now back to our regularly scheduled programming

'''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:

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.

have_posts()) : $my_query->the_post();

$do_not_duplicate = $post->ID; ?>

<!-- Do stuff... -->

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.

ID == $do_not_duplicate ) continue;?>

<!-- Do stuff... -->

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:

have_posts()) : $my_query->the_post();

$do_not_duplicate = $post->ID;?>

<!-- Do stuff... -->

<!-- Do other stuff... -->

ID == $do_not_duplicate ) continue; ?>

<!-- Do stuff... -->

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 [http://codex.WordPress.org/Template_Hierarchy 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

have_posts()) : $my_query->the_post();

$do_not_duplicate = $post->ID;?>

with

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

ID ==

$do_not_duplicate ) continue; ?>

with

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:

$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.

== Loop annidati ==

Annidare i Loop significa eseguire un secondo Loop prima di terminare il primo. Ciò può risultare utile ad esempio per visualizzare un elenco di articoli tramite uno [[Shortcode API|shortcode]].

$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();

È necessario azzerare il Loop principale dopo il Loop annidato in modo che le variabili globali abbiano nuovamente i valori corretti.

==Fonti (in inglese)==

La sezione sui Loop multipli è una combinazione della [http://comox.textdrive.com/pipermail/hackers/2005-January/003578.html discussione] sul Loop fra [http://boren.nu Ryan Boren] e [http://www.alexking.org Alex King's] sulla [[Mailing Lists#Hackers|Hackers Mailing List]] ed anche di un tutorial scritto da [http://www.maxpower.ca/wordPress-hack-sticky-adhesive-kubrick/2005/05/03/ MaxPower]. L'esempio di Loop annidati è stato ispirato da [http://lists.automattic.com/pipermail/wp-hackers/2010-May/032064.html un'altra discussione] sulla mailing list e daun articolo di [http://www.nkuttler.de/2010/05/30/wordpress-loop-inside-a-loop/ Nicolas Kuttler].

==Altre risorse sul Loop (in inglese)==

Per conoscere meglio il Loop di WordPress Loop ed i vari tag dei template che operano solo con il Loop ecco alcune risorse utili.

* [[The Loop in Action]]

* [[Template Tags]]

* [[Templates|Using the Loop in Template Files]]

* [http://www.slideshare.net/mitcho/getting-into-the-loop Getting Into The Loop] - (slides) an introduction to how plugins and themes can modify the Loop

[[Category:Design and Layout]]

[[Category:Advanced Topics]]

{{Copyedit}}

[[Category:UI Link]]

[[Category:it:EN Link da sistemare]]

Show more