Você precisa personalizar a forma como os arquivos do WordPress são exibidos na barra lateral?
O widget de arquivos padrão do WordPress oferece personalização limitada. Talvez você queira que seus arquivos de posts usem menos espaço, exibam mais informações ou tenham uma aparência mais atraente.
Neste artigo, mostraremos como personalizar a exibição dos arquivos do WordPress em sua barra lateral.
Por que personalizar a exibição dos arquivos do WordPress em sua barra lateral?
Seu site WordPress vem com um widget de arquivos que permite exibir links de arquivos de postagens mensais do blog em uma barra lateral.
O widget tem duas opções de personalização: você pode exibir a lista de arquivos como um menu suspenso e pode exibir a contagem de postagens de cada mês.
No entanto, talvez você queira exibir a lista de arquivos da barra lateral de forma diferente. Por exemplo, à medida que seu site cresce, a lista padrão pode se tornar muito longa ou você pode querer facilitar a navegação dos visitantes.
Vamos dar uma olhada em algumas maneiras de personalizar a exibição dos arquivos do WordPress na barra lateral:
- Criação de arquivos compactos
- Exibição de arquivos em um contorno recolhível
- Limitação do número de meses de arquivos exibidos
- Listagem de arquivos diária, semanal, mensal ou anual
- Exibição de arquivos mensais organizados por ano
Criação de arquivos compactos
Se sua lista de arquivos estiver muito longa, você poderá criar um arquivo compacto que exiba suas postagens usando muito menos espaço.
Você precisará instalar e ativar o plug-in Compact Archives, que é desenvolvido e mantido pela equipe do WPBeginner. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.
Após a ativação, você pode adicionar os arquivos compactos a um post, página ou widget usando o bloco “WPBeginner’s Compact Archives”.
A lista compacta de arquivos economiza espaço vertical por ser um pouco mais larga. Isso significa que ela pode se encaixar melhor em um rodapé ou em uma página de arquivos do que em uma barra lateral.
No entanto, o plug-in é bastante configurável e você pode torná-lo mais restrito, exibindo apenas a primeira inicial ou um número para cada mês. Você pode saber mais em nosso guia sobre como criar arquivos compactos no WordPress.
Exibição de arquivos em um esboço recolhível
Outra maneira de lidar com longas listas de arquivos é exibir um esboço recolhível dos anos e meses em que você publicou posts no blog.
Para fazer isso, você precisa instalar e ativar o plug-in Collapsing Archives. Após a ativação, você precisa visitar a página Appearance ” Widgets e adicionar o widget “Compact Archives” à sua barra lateral.
O widget Collapsing Archives usa JavaScript para recolher seu arquivo por ano. Seus usuários podem clicar nos anos para expandi-los e visualizar os arquivos mensais. Você pode até mesmo tornar os arquivos mensais recolhíveis e permitir que os usuários vejam os títulos das postagens embaixo.
Você pode saber mais consultando o Método 1 em nosso guia sobre como limitar o número de meses de arquivo exibidos no WordPress.
Veja como ele aparece em nosso site de demonstração.
Limitação do número de meses de arquivo exibidos
Uma terceira maneira de impedir que sua lista de arquivos fique muito longa é limitar o número de meses exibidos, por exemplo, aos últimos seis meses.
Para fazer isso, você precisará adicionar código aos arquivos do seu tema do WordPress. Se você nunca fez isso antes, consulte nosso guia sobre como copiar e colar código no WordPress.
A primeira etapa é adicionar o seguinte trecho de código ao seu arquivo functions.php, em um plug-in específico do site ou usando um plug-in de trechos de código.
// 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');
Você pode alterar o número de meses exibidos editando o número na linha 6. Por exemplo, se você alterar o número para “12”, serão exibidos 12 meses de arquivos.
Agora você pode ir para a página Appearance ” Widgets e adicionar um widget “HTML personalizado” à barra lateral. Depois disso, você deve colar o seguinte código na caixa do widget:
<ul>
[wpb_custom_archives]
</ul>
Depois de clicar no botão “Atualizar”, sua barra lateral exibirá apenas seis meses de arquivos.
Para obter mais detalhes, consulte o Método 3 em nosso guia sobre como limitar o número de meses de arquivo exibidos no WordPress.
Arquivos de listagem Diária, Semanal, Mensal ou Anual
Se quiser ter mais controle sobre como seus arquivos são listados, o plug-in Annual Archive o ajudará. Ele permite que você liste seus arquivos diariamente, semanalmente, mensalmente, anualmente ou em ordem alfabética, e pode agrupar as listas por década.
Comece instalando e ativando o plug-in Annual Archive. Depois disso, você pode ir para a página Appearance ” Widgets e arrastar o widget Annual Archive para sua barra lateral.
Você pode dar um título ao widget e, em seguida, selecionar se deseja exibir uma lista de dias, semanas, meses, anos, décadas ou publicações. Você pode rolar para baixo até outras opções para limitar o número de arquivos exibidos, escolher uma opção de classificação e adicionar texto adicional.
Se você navegar até Settings ” Annual Archive, poderá personalizar ainda mais a lista de arquivos usando CSS personalizado.
Exibição de arquivos mensais organizados por ano
Certa vez, estávamos trabalhando no design do site de um cliente que precisava de arquivos mensais organizados por ano na barra lateral. Isso foi difícil de codificar porque o cliente só queria mostrar o ano uma vez à esquerda.
Conseguimos modificar alguns códigos de Andrew Appleton. O código de Andrew não tinha um parâmetro de limite para os arquivos, portanto, a lista mostraria todos os meses do arquivo. Adicionamos um parâmetro de limite que nos permitiu exibir apenas 18 meses em um determinado momento.
O que você precisa fazer é colar o seguinte código no arquivo sidebar.php
do seu tema ou em qualquer outro arquivo em que queira exibir arquivos personalizados do WordPress:
<?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; ?>
Se você quiser alterar o número de meses exibidos, precisará editar a linha 19, onde o valor atual de $limit está definido como 18.
Você também pode mostrar a contagem de postagens em cada mês adicionando este trecho de código em qualquer lugar entre as linhas 12 e 16 do código acima:
<?php echo $month->post_count; ?>
Você precisará usar CSS personalizado para exibir a lista de arquivos corretamente em seu site. O CSS que usamos no site do nosso cliente era mais ou menos assim:
.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;}
Esperamos que este tutorial tenha ajudado você a aprender como personalizar a exibição dos arquivos do WordPress em sua barra lateral. Talvez você também queira saber como instalar o Google Analytics no WordPress ou conferir nossa lista de maneiras comprovadas de ganhar dinheiro com blogs no WordPress.
Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.
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!
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!
WPBeginner Support says
Hello,
Please see our article on how to limit archives in WordPress.
Administrador
Jaswinder says
Thanks a lot for the code. Its a life saver.
Carla Izumi Bamford says
Thanks for this post, very helpful.
Margaret says
This was extremely helpful! Thank you so much. Did exactly what I needed it to.
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
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?
Jason Wofford says
The code is working perfectly but how can I add Days to each of the months?
Tony Lewis says
did not work for me seems to be missing some css
Xavier says
Is this code no longer working for anyone else out there??
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 ?
Eldad says
Just wanted to beem thanks
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.
WPBeginner Support says
Try creating it with conditional tags on date based archives templates:
Look codex for is_archive single_month_title
Administrador
tobias says
Not the foreach() loop, the MySQL query should have a limit!
Jessica says
Is there a way for the archive be be daily or even weekly rather than just by month?
Editorial Staff says
You can use the calendar widget in WordPress.
Administrador
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.
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
Asher Charles says
Great little pice of code, been looking for a way to better display archives. Cheers
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!
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.
Editorial Staff says
Thank you for this suggestion. Updated the code.
Administrador
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.
Editorial Staff says
Take the first snippet and convert it into a function. Then use this article to create a shortcode:
https://www.wpbeginner.com/wp-tutorials/how-to-add-a-shortcode-in-wordpress/
Administrador
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
Editorial Staff says
That is indeed weird. We have this running fine on a client’s website.
Administrador
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.
Editorial Staff says
Yes, you can add the counts of all the months in a year and display it if you want.
Administrador
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
Ryan says
Hey Craig,
I am not sure where to put
post_date > YEAR(CURDATE())
Thanks
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
Ryan says
Thank you craig, that seems to have fixed the issue.
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
mary says
how to display the days?
Editorial Staff says
You want to display all 30 days for all the months? Or do you just want to display the days? You might be better of using the built-in calendar widget.
Administrador
Akshat Goel says
Great post!! Saved my day!
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.
wpbeginner says
@sgclark That sounds good. Will have to test out his plugin and then add it in this article
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)
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…
sgclark says
Justin Blanton created a neat WordPress plug in called SmartArchives. I am sure you could dig into his CSS file as well to play with the display and you don’t have to worry about all the extra code on the Sidebar PHP page. – http://hypertext.net/projects/smartarchives