There’s a handy function in WordPress called wp_get_archives(). With it we can create a lot of useful output with just a few lines of code.
To list all articles ever published on a site, we can do this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|// list all articles on this site|
|$args = array(|
|'type' => 'postbypost',|
|'limit' => '',|
|'format' => 'html',|
|'before' => '',|
|'after' => '',|
|'show_post_count' => false,|
|'echo' => 1,|
|'order' => 'DESC'|
|wp_get_archives( $args );|
Here we setup a list of arguments and then give it to the function, which in turn gives us a nicely formatted list of every published article.
If we set the show_post_count argument to true, and replace the type argument to something like “yearly” or “monthly”, we’ll get clickable a list similar to this:
- April 2015 (20)
- March 2015 (11)
- February 2015 (2)
- January 2015 (7)
- December 2014 (4)
- November 2014 (12)
The number in brackets shows up when the show_post_count argument is set to true instead of false.
We can even find out how many articles have been published on the entire site by using the wp_count_posts() function. Here’s how to use it:
$totalPosts = wp_count_posts()->publish;
$totalPosts now holds the amount published posts. We can also query drafts or posts of any particular post type too if we wanted to (such as all status updates or video posts).