Imprimer le numéro d'index de poste actuel dans la boucle
6 réponses
- votes
-
- 2012-07-17
Enfait,je veux attribuer desidentifiants selon l'index des articles!
Voici votre code quej'aimodifié.
<?php global $wp_query; $posts = $woo_options['woo_latest_entries']; query_posts('post_type=post&category_name=company'); if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++; $index = $wp_query->current_post + 1; ?> <div id="my_post_<?php echo $index; ?>"> <!-- Post Content Goes Here --> </div> <?php endwhile; endif; ?>
Actually I want to assign ID's as per post index !
Here's your code that I modified.
<?php global $wp_query; $posts = $woo_options['woo_latest_entries']; query_posts('post_type=post&category_name=company'); if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++; $index = $wp_query->current_post + 1; ?> <div id="my_post_<?php echo $index; ?>"> <!-- Post Content Goes Here --> </div> <?php endwhile; endif; ?>
-
Il semble que cette réponse afourni l'essence de la réponse qui a conduit à la solution.It seems like this answer provided the essence of the answer that lead to the solution.
- 0
- 2016-03-30
- New Alexandria
-
- 2011-06-23
Si c'estjuste une choseesthétiqueet que vousn'avezpasbesoin d'utiliser la variable countpour un codagepluspoussé,vouspouvez simplementenvelopper vosmessages dans unebalise
ol
:<?php if ( have_posts() ) : ?> <ol> <?php while ( have_posts() ) : the_post(); ?> <li> <!-- Post Content Goes Here --> </li> <?php endwhile; ?> </ol> <?php endif; ?>
If it's just an esthetic thing and you don't need to use the count variable for further coding, you can just wrap your posts in an
ol
tag :<?php if ( have_posts() ) : ?> <ol> <?php while ( have_posts() ) : the_post(); ?> <li> <!-- Post Content Goes Here --> </li> <?php endwhile; ?> </ol> <?php endif; ?>
-
Enfait,je veux attribuer desidentifiants selon l'index depublication!Actually I want to assign ID's as per post index !
- 0
- 2011-06-23
- MANnDAaR
-
@MANnDAaR,c'estexactement ce qu'ilfait.Si votreboucle contient 10 articles,vous verrez une liste ordonnée,numérotée de 1 à 10. (voir l'exemple [ici] (http://www.scriptingmaster.com/html/ordered-list.asp))@MANnDAaR, that's exactly what it does. If your loop has 10 posts, you'd see an ordered list, numbered from 1 to 10. (see example [here](http://www.scriptingmaster.com/html/ordered-list.asp))
- 0
- 2011-06-23
- mike23
-
- 2011-06-23
pour une raison quelconque,vous avez déjà une variable de compteur dans laboucle;si celan'estpas utilisé à d'autresfins,faites-en simplement écho:
<?php echo $count.'.'; ?> /// Post Content Goes Here //
for some reason, you already have a counter variable in the loop; if this is not used for other purposes, simply echo it:
<?php echo $count.'.'; ?> /// Post Content Goes Here //
-
Absolument.C'esttout ce quej'avais àfaire.Utilisez votre variable $ count quiest déjà là.MerciAbsolutely. This is all I had to do. Use your $count variable that's already there. Thanks
- 0
- 2020-06-28
- anthonyCam
-
- 2012-07-17
Salut,je suistombé sur cefil,je me demandais commentfaire ça aussi.J'ai découvert que c'était vraimentfacile.Dans lefichier demodèleprincipal,parexempleindex.php,déclarez une variable $post_idx avant laboucle,et dans laboucle,incrémentez que var.Comme ceci:
<?php $post_idx = 0; while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); $post_idx++; ?> <?php endwhile; ?>
Ensuite,dans votremodèle de contenu (parexemple content.php) quiestexécuté à chaquefois dans laboucle,rendez simplement $post_idxglobalet ensuite utilisez-le selon vosbesoins:
global $post_idx; print "<p>{$post_idx}</p>";
C'esttout!
Hi I bumped onto this thread, wondering how to do that too. Found out it's bloody easy. In the main template file, for example index.php, declare a variable $post_idx before the loop, and within the loop increment that var. Like this:
<?php $post_idx = 0; while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); $post_idx++; ?> <?php endwhile; ?>
Then in your content template (for example content.php) that is executed everytime within the loop, just make $post_idx global and then use it to your needs:
global $post_idx; print "<p>{$post_idx}</p>";
That's it!
-
Vous devezpréfixer les variablesglobalespour éviter les collisions denoms.You should prefix global variables to avoid naming collisions.
- 0
- 2012-10-10
- fuxia
-
- 2016-10-24
Je cherchais àfaire lamême chose,maisen dehors de laboucle.Engros,je voulaispouvoirtrouver l'index d'un article àpartir de sonidentifiant.Voici ce quej'aitrouvé:
<?php function sleek_get_post_index ($post) { $allPosts = get_posts([ 'post_type' => $post->post_type, 'numberposts' => -1 ]); $index = 0; foreach ($allPosts as $p) { $index++; if ($p->ID == $post->ID) { break; } } return $index; }
C'étaitpurementpour la conception car le client voulait desnuméros à côté des articles,même si l'article étaitpar lui-même dans uneboîte de "publicationen vedette".J'ai également ajouté un zéronon significatifen utilisant:
<?php echo str_pad(sleek_get_post_index($post), 2, '0', STR_PAD_LEFT) ?>
.I was looking to do the same thing, but outside the loop. Basically I wanted to be able to find out the index of a post from its ID. Here's what I came up with:
<?php function sleek_get_post_index ($post) { $allPosts = get_posts([ 'post_type' => $post->post_type, 'numberposts' => -1 ]); $index = 0; foreach ($allPosts as $p) { $index++; if ($p->ID == $post->ID) { break; } } return $index; }
This was purely for design as the client wanted numbers next to the posts, even if the post was by itself in a "featured post" box. I also added a leading zero using:
<?php echo str_pad(sleek_get_post_index($post), 2, '0', STR_PAD_LEFT) ?>
. -
- 2017-07-25
Même si cette questionest ancienne,je laposeraiici au cas où quelqu'unprovenant d'une recherche Google auraitbesoin d'une réponseplusflexible.
Aufil dutemps,j'ai développé une solutionpour être
WP_Query
ou agnostique aux requêtesglobales. Lorsque vous utilisez uneWP_Query
personnalisée,vous êtes limité àn'utiliser queinclude
ourequire
pourpouvoir utiliser les variables sur votre$ custom_query
,mais dans certains cas (qui sont laplupart des caspourmoi!),lesparties demodèle queje crée sontparfois utilisées dans une requêteglobale (comme desmodèles d'archive) ou dans un codeWP_Query > (commeinterroger untype depublicationpersonnalisé sur lapage d'accueil). Cela signifie quej'aibesoin d'un compteurpour êtreglobalement accessible quel que soit letype de requête. WordPressne le rendpas disponible,mais voici comment yparvenirgrâce à quelques crochets.
Placez ceci dans votrefunctions.php
/** * Créez un compteurglobalement accessiblepourtoutes les requêtes * Mêmenouvelle WP_Querypersonnalisée! */ //Initialisez vos variables add_action ('init',fonction () { global $ cqc; $ cqc=-1; }); //Au début de laboucle,assurez-voustoujours que le compteurest -1 //C'estparce que WP_Query appelle "next_post"pour chaquemessage, //mêmepour lepremier,qui s'incrémente de 1 //(ce qui signifie que lepremiermessage sera 0 commeprévu) add_action ('loop_start',fonction ($ q) { global $ cqc; $ cqc=-1; },100,1); //A chaqueitération d'uneboucle,ce hookest appelé //Nous stockons le compteur de l'instance actuelle dansnotre variableglobale add_action ('the_post',function ($p,$ q) { global $ cqc; $ cqc=$ q- >poste_actuel; },100,2); //A chaqueextrémité de la requête,onnettoieen définissant le compteur sur //le compteur de la requêteglobale. Celapermet à la variablepersonnalisée $ cqc //à définir correctement dans lapageprincipale,lapublication ou la requête,même après //après avoirexécuté une WP_Querypersonnalisée. add_action ('loop_end',fonction ($ q) { global $ wp_query,$ cqc; $ cqc=$ wp_query- > current_post; },100,1);
Labeauté de cette solutionest que,lorsque vousentrez dans une requêtepersonnaliséeet que vous revenez dans labouclegénérale,elle va être réinitialisée aubon compteur detoutefaçon. Tant que vous êtes à l'intérieur d'une requête (ce quiesttoujours le cas dans WordPress,vousne le saviezpas),votre compteur sera correct. C'estparce que la requêteprincipaleestexécutée avec lamême classe!
Exemple:
global $ cqc; while (have_posts ()):the_post (); echo $ cqc;//Affiche 0 letitre(); $ custom_query=new WP_Query (array ('post_type'=> 'portfolio')); while ($ custom_query- > have_posts ()): $ custom_query- >the_post (); echo $ cqc;//Affiche 0,1,2,34 letitre(); en attendant; echo $ cqc;//Affiche ànouveau 0 en attendant;
Even if this question is old, I'll lay this here in case someone coming from a Google Search needs a more flexible answer.
Over the time, I developped a solution to be
WP_Query
or global query agnostic. When you use a customWP_Query
, you are confined to use onlyinclude
orrequire
to be able to use the variables on your$custom_query
, but in some cases (which are most cases for me!), the template parts I create are some times used in a global query (such as archive templates) or in a customWP_Query
(like querying a custom post type on the front page). That means that I need a counter to be globally accessible regardless of the kind of query. WordPress doesn't make this available, but here's how to make it happen thanks to some hooks.Place this in your functions.php
/** * Create a globally accessible counter for all queries * Even custom new WP_Query! */ // Initialize your variables add_action('init', function(){ global $cqc; $cqc = -1; }); // At loop start, always make sure the counter is -1 // This is because WP_Query calls "next_post" for each post, // even for the first one, which increments by 1 // (meaning the first post is going to be 0 as expected) add_action('loop_start', function($q){ global $cqc; $cqc = -1; }, 100, 1); // At each iteration of a loop, this hook is called // We store the current instance's counter in our global variable add_action('the_post', function($p, $q){ global $cqc; $cqc = $q->current_post; }, 100, 2); // At each end of the query, we clean up by setting the counter to // the global query's counter. This allows the custom $cqc variable // to be set correctly in the main page, post or query, even after // having executed a custom WP_Query. add_action( 'loop_end', function($q){ global $wp_query, $cqc; $cqc = $wp_query->current_post; }, 100, 1);
The beauty of this solution is that, as you enter in a custom query and come back in the general loop, it is going to be reset to the right counter either way. As long as you are inside a query (which is always the case in WordPress, little did you know), your counter is going to be correct. That is because the main query is executed with the same class!
Example :
global $cqc; while(have_posts()): the_post(); echo $cqc; // Will output 0 the_title(); $custom_query = new WP_Query(array('post_type' => 'portfolio')); while($custom_query->have_posts()): $custom_query->the_post(); echo $cqc; // Will output 0, 1, 2, 34 the_title(); endwhile; echo $cqc; // Will output 0 again endwhile;
Jetravaille sur WordPress oùj'ai le code suivantpour obtenir les articlesen boucle.
Quelle sortiepublie dans Loops quelque chose comme ça ...
Ce queje veux,c'estimprimer lenuméro d'index des articles actuels dans laboucle. Exemple
Commentpuis-je yparvenir? Merci.
Ohh! Jepeux lefaire de cettefaçon ..
Y a-t-il une autre/meilleurefaçon?