How to count the number of archives there are

Notes:

  • Currently you’re echo-ing the output of wp_get_archives(). In order to return it, we must set the echo input parameter to false.

  • You’re assuming the output of wp_get_archives() is an array, but it’s a string.

Workaround:

Here’s one way, by counting the <li> instances, with the html format:

$args = [
  'parent'     => 0,
  'hide_empty' => 0,
  'echo'       => 0,
  'format'     => 'html',
];

$archive_count = substr_count( wp_get_archives( $args ), '<li>' );

Here we assume the <li> isn’t modified by the get_archives_link filter.

Update:

Here’s another approach by using the get_archives_link filter to tick the counter. This should be able to handle the counting for all types of wp_get_archvies().

Let’s create a general wrapper of wp_get_archives(), to get both the output and the count as well.

First we create an instance of MyArchive:

$myarchive = new MyArchive;

Then we generate it with the relevant arguments:

$myarchive->generate( $args );

To get the count we use:

$archive_count = $myarchive->getCount();

and we get the output with:

$archive_html = $myarchive->getHtml();

Here we define the MyArchive wrapper as (demo):

class MyArchive
{
    private $count;
    private $html;

    public function getCount()
    {
        return (int) $this->count;
    }
    public function getHtml()
    {
        return $this->html;
    }
    public function generate( array $args )
    {
        $this->count = 0;

        // Make sure we return the output
        $args['echo'] = false;  

        // Do the counting via filter
        add_filter( 'get_archives_link',    [ $this, 'getArchivesLink' ] );

        // Generate the archives and store it
        $this->html = wp_get_archives( $args );

        // Remove filter
        remove_filter( 'get_archives_link', [ $this, 'getArchivesLink' ] );

        return $this;
    }       
    public function getArchivesLink( $link )
    {
        $this->count++;
        return $link;
    }
}