I am trying to add a filter on my custom theme based on post month, similar with the archives but with some differences.
What is the best way to get a list of months in witch we have posts?
Thanks,
Alex
I used the following query:
$wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts
FROM $wpdb->posts
WHERE post_type = 'post' AND post_status = 'publish'
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC"
Could not use the wp_get_archives
function because it returns only the following formats:
html - In HTML list (<li>) tags and before and after strings. This is the default.
option - In select (<select>) or dropdown option (<option>) tags.
link - Within link (<link>) tags.
custom - Custom list using the before and after strings.
Core can’t help you here. You’ll have to do a…
Custom Query
Here’s a save query, that I use on admin UI screens to get the total amounts of month with posts to use them in the custom pagination. Pay attention that I query not only for the published posts, but take into consideration that there might be some restriction set and apply it then.
Result
You’ll then be able to inspect your result
Which might look like the following:
You are then able to loop through it or simply grab the first or last array item to get the range. Counting –
count( $total_page_dates )
– would tell you how many month you got, etc. Keep in mind that every array value is anobject
, so you have to access it like thisTry wp_get_archives()
Last Twelve Months
Displays archive list by month, displaying only the last twelve.
Last Fifteen Days
Displays archive list by date, displaying only the last fifteen days.
Last Twenty Posts
Displays archive list of the last twenty most recent posts listed by post title.
For a non-formatted solution, consider using query_posts()
This is the query that wp_get_archive is internally using for month archives
and you are doing same thing, except that using distinct and group by together.