Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coupe WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Comment afficher un nombre limité d’identifiés après les publications dans votre thème WordPress

Note éditoriale : Nous percevons une commission sur les liens des partenaires sur WPBeginner. Les commissions n'affectent pas les opinions ou les évaluations de nos rédacteurs. En savoir plus sur Processus éditorial.

Récemment, on nous a demandé comment afficher un nombre limité d’identifiés après chaque publication dans votre thème WordPress. Normalement, vous utilisez la fonction the_tags() pour afficher un lien vers les identifiants auxquels une publication appartient. Cependant, cette fonction n’a pas de paramètre pour limiter le nombre de tags identifiés. Ainsi, si votre publication comporte 12 identifiants et que votre thème ne peut en afficher que 5, cela risque de ne pas être très esthétique. Beaucoup de gens se contentent de limiter l’utilisation des identifiants, ou ne l’incluent même pas dans les modèles. Mais dans cet article, nous allons vous afficher comment vous pouvez limiter le nombre d’identifiants après les publications dans votre thème WordPress sans limiter le nombre d’identifiants que vous ajoutez à chaque article.

Modification : Apparemment, après avoir écrit cet article, le plus génial des Google (@otto42) a répondu sur mon compte Google+ pour me faire savoir qu’il y a une façon plus simple d’accomplir cela.

Tout d’abord, vous devez ouvrir le fichier functions.php de votre thème et ajouter cette fonction :

add_filter('term_links-post_tag','limit_to_five_tags');
function limit_to_five_tags($terms) {
return array_slice($terms,0,5,true);
}

Vous pouvez modifier le nombre de 5 pour le nombre maximum que vous souhaitez.

Ensuite, ouvrez votre loop.php, single.php, index.php, ou l’endroit où vous voulez ajouter ces identifiants de publication (doit être à l’intérieur d’une boucle de publication), puis collez le code suivant :

<?php the_tags() ?>

C’est certainement beaucoup plus simple que ce que j’avais trouvé et que je vais laisser dans cette publication pour ceux que ça intéresse.

Ancienne méthode compliquée

Tout ce que vous avez à faire est de coller le code suivant dans le fichier de votre thème (à l’intérieur de la boucle de publication) :

<?php
$posttags = get_the_tags();
$count=0; $sep='';
if ($posttags) {
	echo 'Tags: ';
	foreach($posttags as $tag) {
		$count++;
		echo $sep . '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a>';
$sep = ', ';
		if( $count > 5 ) break; //change the number to adjust the count
	}
}
?>

Le code ci-dessus affichera 6 identifications dans le thème. Si vous souhaitez afficher moins d’identifiants ou plus d’identifiants, il vous suffit d’ajuster la ligne $count > 5 avec le nombre que vous souhaitez. Rappelez-vous, même si le nombre de comptage est supérieur à 5, nous voyons 6 identifications. C’est parce que le compte commence à 0. Donc, si vous voulez afficher uniquement 4 identifiants, le nombre doit être de 3.

Si vous voulez modifier le séparateur, vous devez modifier la ligne 9. Le code actuel sépare les balises par des virgules. Vous pouvez également personnaliser le style en ajoutant des divs, des éléments de liste ou tout autre élément que vous souhaitez.

Divulgation : Notre contenu est soutenu par les lecteurs. Cela signifie que si vous cliquez sur certains de nos liens, nous pouvons gagner une commission. Consultez comment WPBeginner est financé, pourquoi cela compte et comment vous pouvez nous soutenir. Voici notre processus éditorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

L'ultime WordPress Toolkit

Accédez GRATUITEMENT à notre boîte à outils - une collection de produits et de ressources liés à WordPress que tous les professionnels devraient avoir !

Reader Interactions

20 commentairesLaisser une réponse

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jilaan says

    Hi Dear Sir,

    sir i want to show randomly tags in widget how can i do that can you give a code which i can added on my function.php file so its showing randomly tags with limit of tags number.

    Thanks

  3. C. Dee says

    This code snippet works great.

    But I need one modification: I need to only show the first three tags that I enter for each blog post. It’s now showing three tags, which is a good step.

    However, I specifically need the first three in the order I specify. This is because of the purpose my website serves and how research data is presented. For example:

    Jennifer Weaver, Case #4455883, New Mexico

    That’s how I’m entering tags: Name, case number, location — and then I have some additional tags. But I only want the first three to display in the entry meta.

    Any suggestions how to do this? The code you shared chooses any order it wants. If my tags are entered like this — one, two, three, four, five — it chooses its own arrangement, such as:

    five, four, one

    Thanks for any help you can offer with this!!

  4. mahmood dabestani says

    Hi.
    this post was very useful.
    But I’m going to create a single page like contact page that it has descriptions about one of my products.
    how can I add my favorite tags about that descriptions in my page?
    in other word how can I add my favorite tags in a single page?
    thank you so much.

  5. joni says

    How for showing random tags?
    example: in my posting blog have 20 tags,
    And i want showing tags number 1, tag number 6, tag number 5,
    and another post have 20 some tags,
    and i want showing tags number 7, 17, 3.
    ETC

  6. Hector P says

    Hello!

    How can I do this « limit the usage of tags ». I want only 3 tags per post/product. And if I select a 4, the number is erased.

    Thank you!

  7. Gabrielle says

    Hi, how can i add if is statement to this function?

    I want to show 5 tags on my main Blog Page(Static page with id=99),
    and then show all tags in single-post page
    Is it possible to combine this function, to work with post category?
    Like Above, i want 5 categories and 5 tags on main page, and full list on single-post…
    Sorry for my English ;/

    • WPBeginner Support says

      For that you will have to edit your theme or child theme’s template file. For tags you can try this code:

      <?php
      $posttags = get_the_tags();
      $count=0;
      if ($posttags) {
      	$output = '';
      	foreach($posttags as $tag) {
      		$count++;
      		$output .= $tag->name . ' ';
      		if( $count >5 ) break;
      	}
      }
      echo $output;
      ?>
      

      Administrateur

  8. Andrew says

    Great info. I came to this site though google search looking for an answer to another problem I need the tag pages to display their tag names as a heading for their individual tag pages. Is there any theme that does this? I am currently using the Divi theme and that feature is not available.

  9. Jill says

    Just FYI…when I pasted those 4 lines in my functions file…my entire site went blank. I about had a panic attack. My hosting company was able to get me back up.

  10. ata says

    What about duplicate content (after Panda update) using tags as same article will be on the post and tag pages.

    Also, i read on wp forum regarding the negative impact of using excessive tags (more than 10 tags) for each post.

    • wpbeginner says

      @ata People should not use Tags for SEO. Tags are built-in to WordPress to improve the usability of your site. You can have 500 tags for one post for all that matters. What is crucial is that you follow, noindex the tags pages. So search engines go to those pages and follow all the links, but don’t index those pages. That will solve the SEO problem. There are too many self-proclaimed SEO experts who don’t know what the heck they are doing. Putting generic statements like the ones you mentioned above are totally wrong as long as you follow what we are saying.

      • ata says

        Actually tags does increase traffic for some sites. You can find proof on Google. Especially long tail keywords attached to a post.

        Not sure how the search engine can find your tag links if it is set as ‘noindex’. Maybe the post url but not the tag links as it doesn’t make sense.

        The ‘generic statement’ was not a statement.at all. If you read my comment, it is more of a query/question so there is no need to bite my head off.

        • wpbeginner says

          @ata First of all let me be clear. I am not biting your head off. The frustration was expressed toward those experts that go along making generic claims like that. WordPress allows for many ways of indexation. Most folks use category as their primary method of archives. In order to prevent duplicate content, you can only use ONE primary method of archive that is indexable. All secondary methods need to be no-index in order to prevent duplicate content.

          We use Categories as our main method of archiving. If you want you can use tags as a primary source of archiving. We find that categories tend to perform better for our blogs. If you want to use tags as a primary source of archiving, then no-index categories, and date based archives. If you are the only author on the site, then you might as well no-index author archives because that will just produce duplicate content as well.Will not argue SEO theories any further in this article because this is a tutorial for design not SEO.

Laisser une réponse

Merci d'avoir choisi de laisser un commentaire. Veuillez garder à l'esprit que tous les commentaires sont modérés selon notre politique de commentaires, et votre adresse e-mail ne sera PAS publiée. Veuillez NE PAS utiliser de mots-clés dans le champ du nom. Ayons une conversation personnelle et significative.