[ad_1]
See WP_Query date parameters, especially year and monthnum, and get_post_meta().
The following PHP, when installed as a plugin for example at wp-content/plugins/shortcode-food-journal/shortcode-food-journal.php, or to your theme’s functions.php, or to a Code Snippet plugin, will enable a shortcode [food-journal] which does what I think you’re describing. It goes from the current month back to January 2000. 2000 can be changed to another starting year on the line foreach( range( date('Y'), 2000 ) as $year ) {
<?php
/**
* Plugin Name: Shortcode: Food Journal
* Description: Output <code>food</code> counts per month and year with shortcode <code>[food-journal]</code>.
* Plugin Author: 𝜑δ•ℂᴹ
* Author URI:
* Plugin URI:
* Version: 1
*/
add_shortcode(
'food-journal',
function( $atts, $content, $shortcode_tag ){
ob_start();
$base_query_args = [
'post_type' => 'journal',
'post_status' => 'published',
'posts_per_page' => -1,
'fields' => 'ids',
];
echo '<ul>';
$food_by_year = [];
// Current year back to 2000 in decending order.
foreach( range( date('Y'), 2000 ) as $year ) {
$food_by_year[ $year ] = 0;
// December to January in decending order.
foreach( range( 12, 1 ) as $month ) {
// Skip months in the current year after the current month.
if ( strtotime( $year . '-' . $month ) > time() ) {
continue;
}
$this_months_post_ids = get_posts(
array_merge(
$base_query_args,
[
'year' => $year,
'monthnum' => $month,
]
)
);
$this_food = $this_months_food = 0;
if ( ! empty( $this_months_post_ids ) ) {
foreach( $this_months_post_ids as $post_id ) {
$this_food = (int) get_post_meta( $post_id, 'food', true );
$this_months_food += $this_food;
$food_by_year[ $year ] += $this_food;
}
}
printf(
'<li>Month %s, Food: %d</li>',
date( 'F Y', strtotime( $year . '-' . $month ) ),
$this_months_food
);
}
printf(
'<li>Year %s, Food: %d</li>',
$year,
$food_by_year[ $year ]
);
}
echo '</ul>';
return ob_get_clean();
}
);
