Como mostrar estatísticas de gráfico do número mensal de postagens no WordPress?
A URL: https://helloacm.com/archives-of-pagesposts/ mostra a lista de postagens históricas e eu adicionei uma figura legal a seguir que traça o número de postagens para cada mês.
posts-gráficos-por-meses-wordpress-php-js
Você pode ver uma atividade difícil nos últimos 12 meses. Sim, ficamos preguiçosos em algum momento do ano. Este post mostra como criar tal página para obter os posts, e o código a seguir pode ser adicionado na mesma página para plotar o gráfico.
Precisamos incluir uma biblioteca javascript de gráfico de terceiros que pode ser encontrada em: https://helloacm.com/js/chart.js
echo '<script language="Javascript" src="<a class="vglnk" target="_blank" href="https://helloacm.com/js/chart.js" rel="nofollow"><span>https</span><span>://</span><span>helloacm</span><span>.</span><span>com</span><span>/</span><span>js</span><span>/</span><span>chart</span><span>.</span><span>js</span></a>"></script>'."n";
global $wpdb; // <a class="vglnk" target="_blank" href="http://helloacm.com" rel="nofollow"><span>helloacm</span><span>.</span><span>com</span></a>
// count the posts number group by each month
$query = "
select
concat(year(`post_date`), '-', month(`post_date`)) as `month`,
count(1) as `cnt`
from
`wp_posts`
where
(post_type='page' or post_type='post') and
`post_status` = 'publish'
group by
`month`
order by
`post_date` desc
limit
12
"; // change this to include more months. the default is 12 months in the past.
$result = array_reverse($wpdb->get_results($query));// reverse the data to get a normal logic flow
if ($result) {
?>
<div id='ReportBarChartContainerMonthly'>
<div id='ReportBarChartComponentMonthly' style='margin: 15px;'>
<canvas id="myChartMonthly" style='max-width:100%;height:auto'></canvas>
</div>
</div>
<script language="Javascript">
var data = {
labels: [
<?php
foreach ($result as $month) {
echo '"'.$month->month.'", ';
}
?>
],
datasets: [
{
label: "Number of Posts",
fillColor: "rgba(200,200,250,0.7)",
strokeColor: "rgba(150,150,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [
<?php
foreach ($result as $month) {
echo '"'.$month->cnt.'", ';
}
?>
]
}
]
};
var ctx = document.getElementById("myChartMonthly").getContext("2d");
var myNewChart = new Chart(ctx).Line(data, {
bezierCurve: true
});
</script>
<?php
}
Salve o arquivo de modelo e limpe o cache, o gráfico será então tornado vivo.
TODO: (1) parâmetro definido para 12 meses por padrão, altere isso de acordo na instrução SQL (2) função inverter array em php inverter os dados de saída para que o eixo correspondente ao tempo (da esquerda para a direita). (3) altere o nome da tabela do WordPress se ela não começar com o prefixo wp.