Pourquoi devrais-je mettre if (have_posts ()), while (have_posts ()) ne suffit pas?
-
-
J'ai voté avant de lirethe_content,the_titleest décisif!I voted up before reading the_content, the_title is decisive!
- 2
- 2013-10-09
- brasofilo
-
Excellente édition (finale).Laplupart desgens utilisent leif et le while directement l'un après l'autre sansjamais utiliser d'autre.Probablement à cause du copier-coller.Excellent (final) edit. Most people use the if and while directly after each other without ever using an else. Likely because of copy & paste.
- 0
- 2018-03-05
- Herbert Van-Vliet
-
3 réponses
- votes
-
- 2013-10-16
Ilest vraimentimpossible d'améliorer la réponse de Chip,maisjuste aller droit aubut:
Utilisez lapartie
if
si vous voulez que quelque chose de différent s'affiche lorsqu'iln'y a aucunmessage .Ceciestparticulièrement utile,parexemple,sur unepage d'archive de date ou de catégorie.Si quelqu'un accède à unepage quin'apas demessages,c'estbien d'avoir unmessage qui le dit,plutôt que rien dutout,car labouclen'estjamaisexécutée.if ( have_posts() ): // Yep, we have posts, so let's loop through them. while ( have_posts() ) : the_post(); // do your loop endwhile; else : // No, we don't have any posts, so maybe we display a nice message echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>"; endif;
It's really impossible to improve on Chip's answer, but just to cut to the chase:
Use the
if
part if you want to have something different show up when there are no posts. This is particularly useful, for example, on a date or category archive page. If someone navigates to a page that has no posts, it's nice to have a message that says so, rather than just nothing appearing at all, because the loop never gets executed.if ( have_posts() ): // Yep, we have posts, so let's loop through them. while ( have_posts() ) : the_post(); // do your loop endwhile; else : // No, we don't have any posts, so maybe we display a nice message echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>"; endif;
-
Et c'esttout ce qu'ilfaut savoir.And this is all one needs to know.
- 0
- 2018-05-18
- Herbert Van-Vliet
-
- 2019-11-28
Il sepeut que certaines considérationsne soientpasinclusesjusqu'àprésent dans les réponses. Iln'estpas recommandé d'omettre l'instructionif.
L'instructionif est couramment utiliséepour:
- affiche quelque chose comme
no posts found
pourindiquer que la catégorieen questionne dispose d'aucun article attribué. - pour décider si le code HTMLenvironnant (comme un ul) doit être affiché avantet après les articles.
Quefaire si unnouveau hookest ajouté?
Un autreproblèmepossible lié à lanon-utilisation de l'instructionif est que si l'équipe wordpress décidait d'ajouter unnouveau hook qui se déclenche sur lepremier appel
$wp_query->have_posts()
,cela déclencherait aumauvaismoment. Et si celaprovoque un comportementinattendu,ce serait votrefaute si vousne suivezpas correctement les spécifications.D'autres développeurs s'attendent à voir une structure spécifiquepour laboucle wordpress
Je suppose que d'autres développeurs s'attendent à voir l'intégralité de laboucle wordpress. Alorspeut-être que c'est unemauvaiseidée de leur demander de rechercher uneinstructionif quin'existepas.
There may be some considerations that are not included in the answers so far. It is not recommended to omit the if statement.
The if statement is commonly used to:
- output something like
no posts found
to indicate that the category in question has no articles assigned to it. - to decide if surrounding html ( like an ul ) should be output before and after the articles.
What if a new hook is added?
Another possible issue of not using the if statement is that if the wordpress team ever decided to add a new hook that triggers on the first
$wp_query->have_posts()
call, it would trigger at the wrong time. And if that causes unexpected behavior it would be your fault for not following the spec properly.Other devs expect to see a specific structure for the wordpress loop
I suppose other developers expect to see the entire wordpress loop. So maybe it is a bad idea to have them searching for an if statement that isn't there.
-
- 2014-10-23
Je vois cela comme une questionfondamentale de lathéorie des structures de contrôle.Leblocinclus dans laboucle whilene s'exécutepasmême unefois si la condition (have_posts ())est évaluée commefausse lapremièrefois.
Ainsi,lebut de
if ( have_posts() )
dans laboucle WordPressest uniquement d'exécuter lafonction have_posts () unefois avant que la condition whilene soit évaluée.Sihave_posts()
n'apas d'effets secondaires,alors leif ( have_posts() )
esttotalementinutile.Sihave_posts()
a deseffets secondaires,vouspouvez simplifier comme suit:<?php have_posts(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?>
I see this as a fundamental question of control structure theory. The enclosed block within the while loop doesn't execute even once if condition (have_posts()) evaluates as false the first time.
So, the the purpose of
if ( have_posts() )
in the WordPress loop is only to execute the function have_posts() once before the while condition is evaluated. Ifhave_posts()
has no side-effects, then theif ( have_posts() )
is totally pointless. Ifhave_posts()
does have side-effects, you could simplify as follows:<?php have_posts(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?>
-
Cette simplificationn'estpas valideen PHP,vous avez uneinstructionelse quin'apas d'instructionif attachée.Aumieux,c'est difficile à lireThat simplification is invalid PHP, you have an else statement that has no attached if statement. At best it's difficult to read
- 3
- 2014-10-23
- Tom J Nowell
-
Le «if»est là à cause du «else» après lui.Aucune autre raison.S'iln'y apas demessages,alors afficher unjolimessage "pas demessages"estmieux que dene rien afficher.The `if` is there because of the `else` after it. No other reason. If there are no posts, then displaying a nice "no posts" message is better than displaying nothing.
- 1
- 2014-10-24
- Otto
J'ai une question sur "laboucle".
Codeextrait de la page du codex WordPress Loop .
Pourquoi devrais-jemettre unepartie
if
? Il semble que s'il y a unebouclewhile
,celafonctionnebien.Dans quel cas unproblème survient s'iln'y apas d'instruction
if
?Modifier
J'ai accepté la réponse de @ Chip.mais honnêtementen disant queje n'aibesoin que de la dernièrepartie.
Je saismaintenant ce queje voulais savoir dema question.