How to add title attribute to archive items

If you look at the source, you will see that the HTML is generated by get_archives_link, which applies the filter get_archives_link. Applying a callback to that filter is probably the most straightforward way to add a title attribute. Unfortunately it is not one of the more friendly filters and requires you to regex the generated markup in order to do much of anything.

Let’s walk through your code.

First, if you want to manipulate the code before printing it you need to set echo to true. As written, the links print to the screen immediately and are not captured in your $html variable.

Secondly, I am not sure why you are trying to wrap the count in a span when you have show_post_count set to false. I’ll assume that is just debugging.

Third, the markup already has a title attribute, which makes this considerably easier. That is where the filter comes in.

function archive_title_attr_wpse_127698($html) {
  $pat = "|title="([^"]+)'|";
  $html = preg_replace($pat,"title="View all posts in archive: $1"",$html);
  return $html;
}
add_filter('get_archives_link','archive_title_attr_wpse_127698');

You can define that callback in functions.php or in a plugin but you probably want to apply it right before the links you want to manipulate and remove it afterwards with remove_filter('get_archives_link','archive_title_attr_wpse_127698');… unless you want to have a global effect.

tech