wp_get_archives: Put span inside anchor tags

I know how it is possible to wrap HTML around anchor elements with the inbuilt arguments for wp_get_archives. Is there a way to alter the content of the anchors in order to add a wrapping span for the anchor text? The intention is to use it for a list of yearly archives on a category (i.e. an automated list of years for which posts exist).

Before:

ul
    lia href="xx"2014/a/li
    lia href="xx"2015/a/li
    lia href="xx"2016/a/li
/ul

After:

ul
    lia href="xx"span2014/span/a/li
    lia href="xx"span2015/span/a/li
    lia href="xx"span2016/span/a/li
/ul

Topic wp-get-archives Wordpress

Category Web


Span outside anchor tags

I think you're looking for the before and after arguments (PHP 5.4+):

wp_get_archives(
    [
        'before' => '<span>',
        'after'  => '</span>'
    ]
);

if you want to wrap the <span> tag around the <a> tag:

<li><span><a href="xx">Link text</a></span></li>

Span inside anchor tags

If you want it inside the anchor tags:

<li><a href="xx"><span>Link text</span></a></li>

then you could use the get_archives_link filter to reconstruct the links to your needs.

Modify the corresponding theme file with (PHP 5.4+):

// Add a custom filter
add_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );

// Archive
wp_get_archives(
    [
        'type'   => 'yearly', // For yearly archive
        'format' => 'html'    // This is actually a default setting
    ]
);  // EDIT the arguments to your needs (I'm not showing the <ul> part here)

// Remove the custom filter
remove_filter( 'get_archives_link', 'wpse_get_archives_link', 10, 6 );

where our filter callback is defined, in the functions.php file in the current theme directory, as:

function wpse_get_archives_link(  $link_html, $url, $text, $format, $before, $after )
{
    if( 'html' === $format )
         $link_html = "\t<li>$before<a href='$url'><span>$text</span></a>$after</li>\n";

    return $link_html;
}

where we've added the span inside the anchor tag.


You can use custom query to modify html or add span

SELECT COUNT(ID) posts, YEAR(post_date) y, MONTH(post_date) m 
    FROM $wpdb->posts 
   WHERE post_status = 'publish'
GROUP BY y, m
  HAVING y = YEAR(NOW())
UNION
  SELECT COUNT(ID), YEAR(post_date) y, 0
    FROM $wpdb->posts
   WHERE post_status = 'publish'
GROUP BY y
  HAVING y < YEAR(NOW())
ORDER BY y DESC, m DESC;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.