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 personnaliser l’affichage des archives WordPress dans votre colonne latérale ?

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.

Vous souhaitez personnaliser l’affichage de vos archives WordPress dans la colonne latérale ?

Le widget d’archives par défaut de WordPress offre peu de possibilités de personnalisation. Il se peut que vous souhaitiez que les archives de vos publications occupent moins d’espace, qu’elles affichent plus d’informations ou qu’elles aient une apparence plus attrayante.

Dans cet article, nous allons vous afficher comment personnaliser l’affichage des archives WordPress dans votre colonne latérale.

How to Customize the Display of WordPress Archives in Your Sidebar

Pourquoi personnaliser l’affichage des archives WordPress dans votre colonne latérale ?

Votre site WordPress est doté d’un widget d’archives qui vous permet d’afficher les liens d’archives des publications mensuelles du blog dans une colonne latérale.

Le widget dispose de deux options de personnalisation : vous pouvez afficher la liste des archives sous forme de menu déroulant, et vous pouvez afficher le nombre de publications pour chaque mois.

The Default WordPress Archives Widget

Toutefois, il se peut que vous souhaitiez afficher différemment votre liste d’archives dans la colonne latérale. Par exemple, au fur et à mesure que votre site grandit, la liste par défaut peut devenir trop longue, ou vous pouvez vouloir faciliter la navigation de vos internautes.

Voyons quelques façons de personnaliser l’affichage des archives WordPress dans votre colonne latérale :

Création d’archives compactes

Si votre liste d’archives est devenue trop longue, vous pouvez créer une archive compacte qui affiche vos publications en utilisant beaucoup moins d’espace.

Vous aurez besoin d’installer et d’activer l’extension Compact Archives qui est développée/développée par l’équipe de WPBeginner. Pour plus de détails, consultez notre guide étape par étape sur l’installation d’une extension WordPress.

Une fois activées, vous pouvez ajouter les archives compactes à une publication, une page ou un widget en utilisant le bloc « WPBeginner’s Compact Archives ».

The Compact Archives Plugin

La liste d’archives compacte enregistre l’espace vertical en étant un peu plus large. Cela signifie qu’elle s’intègre mieux dans un pied de page ou une page d’archives que dans une colonne latérale.

Cependant, l’extension est assez configurable et vous pouvez la rendre plus étroite en affichant uniquement la première initiale ou un nombre pour chaque mois. Vous pouvez en savoir plus dans notre guide sur la création d’archives compactes sur WordPress.

Affichage des archives dans un plan repliable

Une autre façon de gérer les longues listes d’archives consiste à afficher un aperçu repliable des années et des mois au cours desquels vous avez publié des articles de blog.

Pour ce faire, vous devez installer et activer l’extension Collapsing Archives. Une fois activé, vous devez vous rendre sur la page Apparence  » Widgets et ajouter le widget ‘Archives compactes’ à votre colonne latérale.

The Collapsing Archives Plugin

Le widget de réduction des archives utilise JavaScript pour replier vos archives par année. Vos utilisateurs/utilisatrices peuvent cliquer sur les années pour les déplier et voir les archives mensuelles. Vous pouvez même rendre les archives mensuelles repliables et permettre aux utilisateurs/utilisatrices de voir les titres des publications en dessous.

Vous pouvez en savoir plus en vous référant à la méthode 1 de notre guide sur la façon de limiter le nombre de mois d’archives affichés dans WordPress.

Voici ce que cela donne sur notre site de démonstration.

Preview of a Collapsing Archive

Limitation du nombre de mois d’archives affichés

Une troisième façon d’éviter que votre liste d’archives ne devienne trop longue est de limiter le nombre de mois affichés aux six derniers mois, par exemple.

Pour ce faire, vous devrez ajouter du code dans les fichiers de votre thème WordPress. Si vous n’avez jamais fait cela auparavant, alors consultez notre guide sur la façon de copier et coller du code dans WordPress.

La première étape consiste à ajouter l’extrait de code suivant à votre fichier functions.php, dans un plugin spécifique au site ou en utilisant un plugin d’extraits de code.

// Function to get archives list with limited months
function wpb_limit_archives() { 
 
$my_archives = wp_get_archives(array(
    'type'=>'monthly', 
    'limit'=>6,
    'echo'=>0
));
     
return $my_archives; 
 
} 
 
// Create a shortcode
add_shortcode('wpb_custom_archives', 'wpb_limit_archives'); 
 
// Enable shortcode execution in text widget
add_filter('widget_text', 'do_shortcode'); 

Vous pouvez modifier le nombre de mois affichés en modifiant le chiffre de la ligne 6. Par exemple, si vous modifiez le nombre en « 12 », 12 mois d’archives seront affichés.

Vous pouvez maintenant vous rendre sur la page Apparence  » Widgets et ajouter un widget  » Outil de personnalisation  » à votre colonne latérale. Après cela, vous devez coller le code suivant dans la boîte du widget :

<ul>
[wpb_custom_archives]
</ul>
Adding Shortcode to a Custom HTML Widget

Une fois que vous aurez cliqué sur le bouton « Mise à jour », votre colonne latérale n’affichera plus que six mois d’archives.

Pour plus de détails, consultez la méthode 3 de notre guide sur la façon de limiter le nombre de mois d’archives affichés dans WordPress.

Archives des listes quotidiennes, hebdomadaires, mensuelles ou annuelles

Si vous souhaitez mieux contrôler la manière dont vos archives sont répertoriées, l’extension Annual Archive vous sera d’une grande aide. Il vous permet de répertorier vos archives quotidiennement, hebdomadairement, mensuellement, annuellement ou par ordre alphabétique, et de regrouper les listes par décennie.

Premiers pas, installez et activez l’extension Annual Archive. Ensuite, vous pouvez vous rendre sur la page Apparence  » Widgets et faire glisser le widget Annual Archive dans votre colonne latérale.

The Annual Archive Plugin

Vous pouvez donner un titre au widget, puis sélectionner l’affichage d’une liste de jours, de semaines, de mois, d’années, de décennies ou de publications. Vous pouvez défiler vers d’autres options pour limiter le nombre d’archives affichées, choisir une option de tri et ajouter du texte supplémentaire.

Si vous naviguez vers Réglages  » Archives annuelles, vous pouvez personnaliser davantage la liste des archives à l’aide d’une feuille de style CSS personnalisée.

Affichage des archives mensuelles classées par année

Une fois, nous avons travaillé sur la conception du site d’un client qui avait besoin d’archives mensuelles classées par année dans la colonne latérale. Cela a été difficile à coder parce que ce client voulait uniquement afficher l’année une fois à gauche.

Displaying Monthly Archives Arranged by Year

Nous avons pu modifier le code d’Andrew Appleton. Le code d’Andrew n’avait pas de paramètre de limitation pour les archives, de sorte que la liste affichait tous les mois d’archives. Nous avons ajouté un paramètre de limitation qui nous a permis d’afficher uniquement 18 mois à un moment donné.

Ce que vous devez faire est de coller le code suivant dans le fichier sidebar.php de votre thème ou dans tout autre fichier où vous souhaitez afficher des archives WordPress personnalisées :

<?php
global $wpdb;
$limit = 0;
$year_prev = null;
$months = $wpdb->get_results("SELECT DISTINCT MONTH( post_date ) AS month ,  YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month , year ORDER BY post_date DESC");
foreach($months as $month) :
    $year_current = $month->year;
    if ($year_current != $year_prev){
        if ($year_prev != null){?>
         
        <?php } ?>
     
    <li class="archive-year"><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/"><?php echo $month->year; ?></a></li>
     
    <?php } ?>
    <li><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>"><span class="archive-month"><?php echo date_i18n("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span></a></li>
<?php $year_prev = $year_current;
 
if(++$limit >= 18) { break; }
 
endforeach; ?>

Si vous souhaitez modifier le nombre de mois affichés, vous devez modifier la ligne 19 où la valeur actuelle de $limit est définie à 18.

Vous pouvez également afficher le nombre de publications pour chaque mois en ajoutant ce bout de code n’importe où entre les lignes 12 à 16 du code ci-dessus :

<?php echo $month->post_count; ?>

Vous devrez utiliser une feuille de style CSS personnalisée pour afficher correctement la liste des archives sur votre site. Le CSS que nous avons utilisé sur le site de notre client ressemblait à ceci :

.widget-archive{padding: 0 0 40px 0; float: left; width: 235px;}
.widget-archive ul {margin: 0;}
.widget-archive li {margin: 0; padding: 0;}
.widget-archive li a{ border-left: 1px solid #d6d7d7; padding: 5px 0 3px 10px; margin: 0 0 0 55px; display: block;}
li.archive-year{float: left; font-family: Helvetica, Arial, san-serif; padding: 5px 0 3px 10px; color:#ed1a1c;}
li.archive-year a{color:#ed1a1c; margin: 0; border: 0px; padding: 0;}

Nous espérons que ce tutoriel vous a aidé à apprendre comment personnaliser l’affichage des archives WordPress dans votre colonne latérale. Vous voudrez peut-être aussi apprendre comment installer Google Analytics sur WordPress, ou consulter notre liste de moyens éprouvés pour gagner de l’argent en bloguant avec WordPress.

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

45 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. AD says

    Is there a way, or a widget of some kind, under the Archives sidebar to have blog posts by title displayed under under the correlating month; versus just the month alone being present that clicks into a new page displaying all posts for that month in their entirety?

    I’m sorry if this has already been answered in the comments. I haven’t had a chance to read them.

    Thank you for any help or direction you can provide my question!

  3. Thomas says

    Hello WPBEGINNER,

    I hope you still have a look at this older post. First many thanks for this great tutorial and code.
    I’ve managed to get

    Year
    January (2)
    February (5)

    But didn’t manage to count the posts per year. How can I do this, so that the year entry shows a number for all post for a year
    year (28) …

    Many thanks for your help!

    Best regards,
    Thomas

  4. Erik says

    Thanks so much for this code! :) it is helping me a lot.

    Any chance to extend this to a specific category? by category id?

    • James says

      It does work at all !!!

      result has nothing to do with example.

      Strange that some guys felt it useful and great.

      What is the issue ?

  5. Xavier Bonet says

    Hi! First thing’s first! Great code! Works perfectly! Thanks!
    I was asking myself if there would be a way to edit the code in order to allow for the, say, 18-month span to move up or down according to what one is viewing? As is, you can only access the last 18 months. But perhaps there would be a way to do this so that when one opens up, for example, month 18 of the list, and the new page is opened, the archive list output by the code above sets month 18 as the middle of a new array showing, say, 9 months before and 7 after (or vice-versa).
    Perhaps my explanation is not too clear. I got the idea when viewing this website here: http://marthabeck.com/. If you scroll down to the menu at the very bottom you will see there are several years available but only those months for the present year are displayed. When one opens up a new year, the months for that year are then displayed. Of course, this is probably another code entirely, but at least it works as a visual example of sort of what I’m talking about.

    • JP Lew says

      I use a calendar, but in addition to that modified the code to output daily archives too, it worked great. Here’s the query:

      $days = $wpdb->get_results(« SELECT DISTINCT DAY( post_date ) AS day , MONTH( post_date ) AS month , YEAR( post_date ) AS year, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = ‘publish’ and post_date <= now( ) and post_type = 'lecture' GROUP BY day , month , year ORDER BY post_date ASC");

      <a href="/year; ?>/month, 1, $day->year)) ?>/month, $day->day, $day->year)) ?> »>month, $day->day, $day->year)) . « ,  » . date_i18n(« F », mktime(0, 0, 0, $day->month, 1, $day->year)) .  »  » . date(« j », mktime(0, 0, 0, $day->month, $day->day, $day->year)) . « ,  » . $queried_year ?>post_count . « ) »; ?>
      //outputs: Thursday, August 22, 2013 (12)

      Thanks for the post by the way, it was exactly what I was looking for. The performance is surprisingly good too.

      • JP Lew says

        ok, your comment system stripped out all my `php` tags essentially rendering that code useless. Anyways, it’s possible and easy, you’ll figure it out. :)

  6. Roelof says

    Hello,

    I like this idea. Can it also be adapted so only articles in a specific category will be in the archives and all the other categories not.

    Roelof Wobben

  7. Carla says

    I’ve looked everywhere for a tutorial on how to customize my archives page. I was able to get my page to produce a list of post titles and post dates, which is a great start. And now I need to figure out how to group them by month, so the page looks like this:

    2013

    May

    This is a post title
    May 28, 2013

    And another post
    May 20, 2013

    I’m not really sure how to do this. Would you have any suggestions? I’ve noticed in the WordPress forum and elsewhere that lots of people want their archives to look like this, but they (like me) haven’t received any help.

    Thank you!

  8. Núria says

    Thanks for this code snipped, it has been very usefull. I only want to add a little bit change that will make the output of the month’ string in the locale language.
    On line 16 you can replace the date() function to date_i18n() function

    – echo date(« F », mktime(0, 0, 0, $month->month, 1, $month->year))
    – echo date_i18n(« F », mktime(0, 0, 0, $month->month, 1, $month->year))

    Thus, the function will return for the march month the string « March » in English, « Marzo » in spanish or « Març » in catalan, only to put some examples, based on the language of the site.

  9. Matt says

    The theme I’m using has a widget for the sidbars. The php file is written in shortcode. How would I convert this to a shortcode to put into the file? Thanks.

  10. Ryan says

    Hey,

    I came across this, just what i was after. But it has a small problem, i have the last two months of posts october and november show in sidebar, i just added a new one in december and its not showing december in the archive list.

    Weird why its not showing the current month

  11. thao_ says

    Is it possible to show the total years’ post_count, as well as the post_count for each month? So you’d still have each months’ post count next to each month, but also the total for the year next to the year. Using your archive image as the example, you’d have 2010 (20) and then the months as the currently display.

  12. craig coffman says

    I think I got it sorted. I moved the « break; » up into the code before it spits out the monthly … . I figured it out after looking at Appleton’s site. His code is slightly different, as you noted. I find it interesting how people can change a single bit of code and the effect is wildly different from such a small edit. To borrow from WP, « Code is Poetry » :)

    I did make one alteration which I wanted to bring to your attention. The above code did not seem to spit out the most current month. That is, my August month of this year would not appear (since we are now in August) but July showed just fine. I altered the SQL statement and now it does appear. I am not sure you want the current month, but if this is an archive perhaps even the current month is archived.

    Here is my change:

    post_date YEAR(CURDATE())

    That seems to pull the month we are currently in. I am no SQL master, so perhaps there is a reason not to do this or even a better way. However it is working for me.

    Thanks for your time on this tutorial. It definitely saved me from further bashing my head against a wall attempting to manipulate wp_get_archives().

    • craig coffman says

      hmm… seems like some code was stripped out. There should be the Greater Than symbol in there, between « post_date » and « YEAR(CURDATE()) ». Let me try again and I hope it takes.

      post_date > YEAR(CURDATE())

      Sorry for the additional post, but a ‘tweak’ doesn’t change anything if the proper code does not display :)

        • craig coffman says

          Ryan –

          Weird. I posted a response on the Float Left site but it does not seem to be there. Here is the file for you to download, showing where the code is located:

          http://www.octoberland.com/fileChute/displayCurrentMonth.zip

          I put the code in the index.php file from my template. It is there because the client wanted it to be on every page. It only grabs the current year’s months. That is, if you went back to 2011 the months displayed would still be 2012.

          I added my code into the ‘WHERE’ line of the MySQL, replacing the code Andy had there.

          Also, I have the standard WP archive function in there as well because my client wanted to display a yearly archive as well. This is not necessary for displaying the current month.

          I hope this helps.

          – Craig

      • craig coffman says

        Ryan –

        Happy it worked for you. It took me several hours (I am not a MySQL developer) to figure that out. Now that it is helped someone else, it was worth the effort :)

        – Craig

  13. zuzanka says

    Hi, I’m using only widget, not extra plugin for archive. I limited number of months, e.g. 2 but I’m expecting to have 2 months and than the rest under « … » or « archive ». I can not find the way how to show the rest. Is here someone who knows this problem? Thanks a lot.

  14. sgclark says

    @wpbeginner The unused months are wrapped in their own unique CSS class, so you can just do a CSS « display:none » for unused months. Then when a post appears in the month, it switches to a different class (via PHP)

  15. wpbeginner says

    @sgclark That plugin sounds good… Wonder how that would work if we don’t want to show the unused months at all. But nonetheless haven’t tried it yet because it is not hosted in the repository…

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.