0

Is there a way to count the number of monthly archives? For example, my site has the 3 monthly archives (jan 2016, feb 2016). So the number should be 2. How I can display the count.

PS: I want to display the count beside the Archives Label in my sitemap

I tried with the following with no success.

<?php 
$args = array(
  'parent' => 0,
  'hide_empty' => 0
  );
$arch_count  = wp_get_archives($args); 

echo count ($arch_count);
?>

Thanks in advance

2

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;
    }
}
2
  • Cool!.. This will do. Thanks a lot for this. I highly appreciate this. – Ayanize May 2 '16 at 13:12
  • I updated the answer with a (hopefully) more general method @Ayanize – birgire May 2 '16 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.