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 créer des modèles de catégories dans 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.

Voulez-vous créer des mises en page de catégories uniques dans WordPress ?

Sur les sites WordPress, il est courant d’utiliser des modèles différents pour les catégories, les identifiants, les types de publications personnalisés et les taxonomies.

Dans cet article, nous allons vous afficher comment créer des modèles de catégories sur WordPress.

Creating category templates in WordPress

Pourquoi créer des modèles de catégories dans WordPress ?

WordPress génère des pages individuelles pour toutes vos catégories. Vous pouvez les voir en visitant une URL comme :

https://example.com/category/news/

La plupart des thèmes WordPress populaires sont livrés avec des modèles intégrés pour mettre en valeur les pages de catégories. Ces modèles mettent en évidence le titre de la catégorie et affichent la description de la catégorie en dessous.

Category page example

Cependant, certains thèmes peuvent ne pas gérer cela de manière aussi agréable, ou vous pouvez vouloir personnaliser vos pages de catégories.

En créant des modèles pour les catégories, vous pouvez ajouter des fonctionnalités spécifiques aux pages des catégories.

Par exemple, vous pouvez permettre aux utilisateurs de s’abonner à des catégories, d’ajouter des images de catégories, d’afficher des descriptions de catégories et de choisir une mise en page différente pour chaque catégorie.

Voyons comment créer des modèles de catégories dans WordPress. Vous pouvez utiliser les liens rapides ci-dessous pour passer aux différentes parties de notre tutoriel :

Hiérarchie des fichiers modèles de WordPress pour les pages de catégories

WordPress dispose d’un puissant système de modèles qui vous permet de créer différents modèles pour différentes sections de votre site.

Lors de l’affichage d’une page, WordPress recherche un modèle dans un ordre hiérarchique prédéfini.

Pour afficher une page de catégorie, il recherche les modèles dans cet ordre : category-slug.php → category-id.php → category.php → archive.php → index.php

Tout d’abord, WordPress recherchera un modèle spécifique à cette catégorie particulière en utilisant le slug de la catégorie. Par exemple, le modèle category-design.php sera utilisé pour afficher la catégorie « Design ».

S’il ne trouve pas de modèle avec un slug de catégorie, WordPress cherchera un modèle avec un ID de catégorie, comme category-6.php. Ensuite, il cherchera le modèle de catégorie générique, qui est généralement category.php.

En l’absence de modèle générique de catégorie, WordPress recherche un modèle générique d’archive, tel que archive.php. Dernier point, il utilisera le modèle index.php pour afficher la catégorie.

Voici notre guide des hiérarchies des modèles WordPress.

WordPress category archive

Créer un modèle de catégorie pour votre thème dans WordPress

Examinons d’abord un modèle typique de category.php :

<?php
/**
* A Simple Category Template
*/

get_header(); ?> 

<section id="primary" class="site-content">
<div id="content" role="main">

<?php
// Check if there are any posts to display
if ( have_posts() ) : ?>

<header class="archive-header">
<h1 class="archive-title">Category: <?php single_cat_title( '', false ); ?></h1>

<?php
// Display optional category description
 if ( category_description() ) : ?>
<div class="archive-meta"><?php echo category_description(); ?></div>
<?php endif; ?>
</header>

<?php

// The Loop
while ( have_posts() ) : the_post(); ?>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>

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

 <p class="postmetadata"><?php
  comments_popup_link( 'No comments yet', '1 comment', '% comments', 'comments-link', 'Comments closed');
?></p>
</div>

<?php endwhile; 

else: ?>
<p>Sorry, no posts matched your criteria.</p>

<?php endif; ?>
</div>
</section>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Supposons maintenant que vous ayez une catégorie appelée « Design » avec le slug « design », et que vous souhaitiez afficher cette catégorie différemment des autres.

Pour ce faire, vous devez créer un Modèle pour cette catégorie particulière. Allez dans Apparence  » Éditeurs/éditrices de thèmes.

Dans la liste des fichiers du thème sur votre droite, cliquez sur category.php.Si vous n’avez pas de fichier category.php à cet endroit, cherchez alors archive.php.

Theme category file editor

Si vous ne trouvez aucun de ces modèles, il y a de fortes chances que vous utilisiez un cadre de thème WordPress et que ce tutoriel ne vous soit pas utile. Nous vous suggérons de vous référer au cadre spécifique que vous utilisez.

Si vous trouvez les fichiers ci-dessus, copiez tout le contenu de category.php et collez-le dans un éditeur de texte comme Notepad. Enregistrez ce fichier sous le nom category-design.php.

Vous devez ensuite vous connecter à votre hébergeur WordPress à l’aide d’un client FTP, puis aller dans /wp-content/themes/votre-thème-courant/ et téléverser votre fichier category-design.php dans le répertoire de votre thème.

Désormais, toutes les modifications apportées à ce Modèle apparaîtront uniquement dans la page d’archive de cette catégorie particulière.

Cette technique vous permet de créer des modèles pour autant de catégories que vous le souhaitez. Il suffit d’utiliser category-{category-slug}.php comme nom de fichier. Vous pouvez trouver les slugs de catégorie en visitant la section des catégories dans la zone d’administration de WordPress.

Voici un exemple de modèle category-slug.php. Notez que nous avons utilisé le même modèle que category.php avec quelques modifications.

Comme nous connaissons déjà la catégorie pour laquelle il sera utilisé, nous pouvons ajouter le titre, la description ou tout autre détail manuellement. Notez également que nous avons utilisé <?php the_excerpt() ; ?> au lieu de <?php the_content() ; ?>.

<?php
/**
* A Simple Category Template
*/

get_header(); ?> 

<section id="primary" class="site-content">
<div id="content" role="main">
<?php
// Check if there are any posts to display
if ( have_posts() ) : ?>

<header class="archive-header">
<?php
// Since this template will only be used for Design category
// we can add category title and description manually.
// or even add images or change the layout
?>

<h1 class="archive-title">Design Articles</h1>
<div class="archive-meta">
Articles and tutorials about design and the web.
</div>
</header>

<?php

// The Loop
while ( have_posts() ) : the_post();
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>

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

 <p class="postmetadata"><?php
  comments_popup_link( 'No comments yet', '1 comment', '% comments', 'comments-link', 'Comments closed');
?></p>
</div>

<?php endwhile; // End Loop

else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
</div>
</section>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Si vous ne souhaitez pas utiliser le modèle category-slug, vous pouvez utiliser le modèle category-id pour créer un modèle pour un ID de catégorie spécifique. Voici comment trouver l’ID d’une catégorie dans WordPress.

Utilisation de balises conditionnelles pour une catégorie

Lorsque vous créez des modèles pour votre thème, vous devez déterminer si vous avez vraiment besoin d’un modèle distinct pour faire ce que vous voulez faire.

Dans certains cas, les modifications que vous souhaitez apporter ne sont pas trop compliquées et peuvent être réalisées à l’aide de marqueurs conditionnels à l’intérieur d’un modèle générique, comme category.php ou même archive.php.

WordPress prend en charge de nombreuses balises conditionnelles que les auteurs/autrices de thèmes peuvent utiliser dans leurs modèles.

Un exemple de balise conditionnelle est is_category(). En utilisant cet identifiant conditionnel, vous pouvez modifier vos modèles pour qu’ils affichent des résultats différents si la condition est identifiée.

Par exemple, supposons que vous ayez une catégorie pour les publications en avant appelée « Featured ».

Vous souhaitez maintenant afficher des informations supplémentaires sur la page d’archive de la catégorie pour cette catégorie particulière. Pour ce faire, ajoutez ce code dans le fichier category.php juste après <?php if ( have_posts() ) : ?>.

<header class="archive-header">

<?php if(is_category( 'Featured' )) : ?>
	<h1 class="archive-title">Featured Articles:</h1>
<?php  else: ?>
	<h1 class="archive-title">Category Archive: <?php single_cat_title(); ?> </h1>
<?php endif; ?>

</header>

Créer un Modèle de Catégorie avec Beaver Themer

Beaver Themer vous permet de créer des Mises en page pour votre thème. Vous pouvez sélectionner les différentes catégories dans lesquelles vous souhaitez utiliser le Modèle, puis les modifier à l’aide d’un outil de glisser-déposer.

Tout d’abord, vous devez vous rendre dans Beaver Constructeur  » Themer Mises en page  » Add New page.

Add new category template

Vous devez lui donner un titre.

Sélectionnez ensuite votre catégorie dans l’option « Emplacement ».

Edit Beaver Themer layout

À partir de là, vous pourrez utiliser le constructeur de pages/éditrices de Beaver Constructeur pour personnaliser la page de présentation de votre catégorie à votre guise.

Beaver Themer fournit de nombreux modules que vous pouvez utiliser et déplacer pour concevoir votre page de présentation des catégories.

Using Beaver Builder to design your category template

Une fois que vous avez terminé, il vous suffit de cliquer sur le bouton « Sélectionné » et de sélectionner « Publier » pour appliquer votre modèle de catégorie.

Vous pouvez maintenant visiter votre site WordPress pour voir le modèle de catégorie en action.

A category template made with Beaver Builder

Nous espérons que cet article vous a aidé à apprendre comment créer des modèles de catégories sur WordPress. Vous pouvez également consulter notre comparatif des meilleurs constructeurs de pages WordPress drag & drop pour créer des mises en page personnalisées et notre guide sur la création d’un site d’adhésion afin de pouvoir restreindre le contenu en fonction des catégories.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

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

58 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. Gwyneth Llewelyn says

    I just wanted to thank you — not only for the clarity of the explanations, but, most importantly, for restricting your code to the essential, while keeping all typical WordPress conventions (in terms of styling) as they were originally coded (even if they have, today, a ‘retro’ style of coding!).

    This simplifies, for beginners and forgetful experienced programmers alike, to fully integrate a category page on a theme that doesn’t support them; because even though every theme does it slightly differently, there is enough common ground for a simple template to do its job while delegating more complex functionalities to theme-specific functions. That is, at least, the case with well-written themes, of course.

    Thanks again!

  3. Muhammad Zeeshan says

    I want to create the same custom page for all categories but I don’t want to create it one by one. If I add a new category in the future, I want the same template for the new category as for the old one. How can I get this?

    • Alexandro Giles says

      You only need to create 1 category.php template, this category template will be used in any category archive that you create.

  4. Daniel says

    Hi – Its a very helpful tutorial but I am trying to show a specific category and its sub categories on a page – How do i do that ?

  5. Barbara says

    I’m putting my question here because it’s the closest topic to what I am looking for. My church is going to put out a newsletter using Constant Contact. Our current newsletter has both short items and longer articles. I want to use short excerpts of the longer articles in the newsletter with a link to the article online. To that end, I have created a category-newsletter and using a plugin Unique Headers have changed the header image. I want now to suppress the H1 in the header, but since the header is called from the post page, the only way I can think of to obtain the result that I want is to do a custom page/post in which I don’t call header.php but include the contents of header.php in my custom post page. I might even want to do a custom footer.

    How do I do that without causing an error?

  6. Steven Denger says

    This is a knowledgable tutorial for making templates – if you are an advanced user of code. This is what I see too much here- an explanation for the advanced users or developers but is of little to no value to beginners. I thought that this was WP BEGINNER – this is hardly a beginners tutorial and was of no help to me what-so-ever.

  7. Daniel says

    Hello, great tutorial. I really want to add a limit of 5 posts per page and have page numbering. Can someone help me with the code?

  8. Chris Smith says

    Thank you so much for writing this article – I was trying so hard to find where the categories were stored for my personal blog site. I had been through every php I could find and searched relentlessly for categories in my FTP/ control panel. Although the advice given here basically said it couldn’t help and i wouldn’t find it useful, it did encourage me to look at the content.php which was in the ‘framework’ directory of the theme. If anyone else is using the free version of the plum theme and wants to know how to do this in ftp, I hope this comment is useful!

  9. Richard Lowe says

    My theme came without a template for categories, tags, etc. So this article is perfect since I want them.

    Question: Would it be best to do this in a child theme so custom changes are not lost if and when the theme is updated?

  10. Borislav says

    For Custom Single Post page templates by category one could make a separated folder called « single » and then put inside all single templates like single-category-slug.php. + the general single.php. There was also necessary to add some code in functions.php. Can you do the same technique for Category page templates, like put all category-slug.php + the general category.php in a map called « category » ? I wonder that just to have a better file oragization istead of having all category-slug.php among all other theme php files like header.php footer.php index.php etc.

  11. rami mike says

    Thanks… that’s very useful. What if i want an archive page that display all the posts from 3 of my 5 categories….
    How can i do that ?

  12. Mark says

    Nice tutorial, I really appreciate the huge investment in wordpress tutorial and also in OptinMonster. But I will like to point out something in the tutorial: In the category template, you forget to echo the single_cat_title(  », false );

    It should be:

    Category:

    Thanks

  13. Dan says

    When I use this template, I get the max set number of posts in the Dashboard, which is 10 posts only. When I select a category I want all of the posts for that category, not only the most recent 10. I tried adding query_posts(‘posts_per_page=50’); at the beginning of the Loop, but when I do that then posts from a different category are appearing in my selection. Any ideas?

  14. Dnil says

    Hi, I have category.php file on my theme. But whenever I view it, it shows only the title and a brief summary of the post. I want to have image of the post instead of text appear below the blog title. Please help me sir. I can’t find a better solution. I’m a newbie at wordpress :( Thank you

  15. Dnil says

    Hi,

    I’m getting real problem on how can I add « Image » in the category page instead of « text »? :( Please is anyone can help me here?

    Here’s my category.php


    Thanks in advance. Please email me on how to fix this stuff.

  16. SevenT says

    Thank you for this helpful post. But when i try a first one code. It make error.
    Parse error: syntax error, unexpected ‘<' in \category.php on line 22

    And the second one is same error on line 31

    What happen? I have checked it.

  17. Lisa says

    I am using Divi 2.1.4. I do not see any archive or category php. Can I use the index.php as the base and modify from there for a custom category page?

  18. JAspen says

    How would I have all my category page templates display on one page? I have 3 different category templates and look great on each single category page, but need them to display all together on one page.

  19. Bruce Bates says

    I solved my problem with your example code. You didn’t close the while loop on line 29 ?>

    29 while ( have_posts() ) : the_post();

  20. Bruce Bates says

    I am trying to create a theme (first time) and I am stuck on the category template. Have things changed as of wordpress 3.9? I literally copied and pasted the code you have here (removing the line numbers), saved the file, and tested it out and I get a fully blank page. Not even an opening html tag is happening when viewing outputted source.

  21. Deepa Govind says

    Hi,

    I am developing a child theme, and want to show a specific image alongside the category description — @ Category Archives page.

    ie, If category = Poetry, SHOW + description + post list
    if category = cooking, SHOW + description + post list
    if category = tutrial, SHOW + description + post list

    I know that we can put the IF-Condition in the category.php’s >> Archive header

    But, my list is pretty long — almost 20 categories
    and I donot want to clutter the actual category.php file

    Is it possible to write a custom function (in myfunc.php)
    and make a call at the category.php??

    Thank you

    • Deepa Govind says

      This is wierd, some of my text in the comment is missing
      so here it is again

      ie, If category = Poetry, SHOW QUILL IMAGE+ description + post list
      if category = cooking, SHOW CHEF IMAGE+ description + post list
      if category = tutrial, SHOW TEACHER IMAGE+ description + post list

  22. Lars says

    Hey! I have trouble with the theme I am developing. I want to show only one category pr. page, but when all posts for all categories shows up on all the pages. How can I show just one category pr. page without having to make a specific page for each page specifying the name of the category?

  23. Muhammed Ashique Kuthini says

    Can i get a function like showposts in this loop ? I am designer and recently came with development. I need to show the most recent post of the selected category in a different style.

  24. Cath says

    This seems straightforward but I’m having problems. I’m creating a child theme from a parent theme. The parent theme has an archive.php file only. In my child folder I want the archive.php for my Archives widget and for my Category widget, I want a category.php file. I’ve copied the archive.php code into a blank php file and saved it as category.php. The archive.php still defaults for both. Am I missing something? Thank you.

    • WPBeginner Support says

      Nope you are not missing anything. category.php should take over when ever a user is browsing a category page. This could happen for a number of reasons. For example WordPress may not be able to identify category.php file. Can you open category.php file in Appearance » Editor. Double check that you have not accidentally saved category.php as category.php.txt. Also check out our guide on creating child themes to make sure that you have created a child theme correctly.

      Administrateur

      • Cath says

        Hi. I am able to open category.php with the Appearance>Editor. Does the category.php file need to be added somewhere? Thank you.

        • Cath says

          Hi. I am able to open category.php with the Appearance>Editor. The file is saved in my child theme with the rest of my files that are working on my site. Do I need to add it to the functions.php file in order for WordPress to use category.php instead of archive.php?

  25. Lex says

    Thanks for your great article. Very helpful.

    I have a custom post type –  »video », and a custom taxonomy – « video_categories » What would be the best way display them? I need a « home » for all videos, and a page that lists videos from a category.

    archive-videos.php – « home » listing page for all videos of all categories
    taxonomy-video_categories.php – a category listing page

    This is what I am thinking about. I feel there should be a better way. At the moment these two files have exactly the same code which is duplication.

    Thanks in advance for sharing your experience

  26. Amit Kumar says

    I liked the Idea of creating different designs for each category page. Can you please tell me how can I achieve a particular design for post under one specific category?

    For eg. All the post under category « Design » will have a particular design format and background etc.

    I would be glad to have any link which can provide any hint related to this.

  27. Mark Roth says

    I’ve been wanting to do this for quite a while. It’s not that I don’t know how to do it, it’s that I keep forgetting…and being distracted by more important projects. Your post is a great reminder…and will be a handy reference point. I’ve added it to my bookmarks. Thanks!

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.