Filtering archive page headings in WordPress 5.5

With WordPress 5.5, theme authors will now be able to easily filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. archive pages headings, so they can use their own HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. markup.

The existing get_the_archive_title hook was previously limited to filter the whole title string used on archive pages. Some contributors pointed out that this filter was not specific enough to address all theme developers needs related to the archive pages headings.

In get_the_archive_title() this change splits the internal $title variable into $title and $prefix.

By using the new get_the_archive_title_prefix filter, the prefix can now be wrapped within custom elements or removed completely.

Basic examples

get_the_archive_title_prefix can be used to filter the archive pages heading prefix. It accepts only one argument, $prefix, which is a string containing the text prefix of the heading.

To replace the archive title prefix with another text, use:

function mytheme_archive_title_prefix( $prefix ){
    $prefix = __( 'Currently viewing archives for:', 'my-theme' ); 
    return $prefix;
}
add_filter( 'get_the_archive_title_prefix', 'mytheme_archive_title_prefix' );

To completely remove the archive title prefix, use:

add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );

This change also wrap the title part with a span element and pass the original title and prefix to the existing get_the_archive_title filter, allowing further customization to the archive titles.

This filter passes the following arguments:

  • $title: Archive title to be displayed
  • $original_title: Archive title without prefix
  • $prefix: Archive title prefix

Here is a sample example of use:

function mytheme_get_the_archive_title( $title, $original_title, $prefix ) {
    $prefix = '<span class="archive-prefix">' . __( 'Currently viewing archives for:', 'my-theme' ) . '</span>';
    $title  = '<span class="archive-title">' . $original_title . '</span>';
    return $prefix . $title;
}
add_filter( 'get_the_archive_title', 'mytheme_get_the_archive_title', 10, 3 );

For full context on this change, see the related tickets: #31237, #38545 and #42768.

Note reviewed by @justinahinon

#5-5, #dev-notes