Using WordPress ‘get_archives_link()’ PHP function

The get_archives_link() WordPress PHP function retrieves archive link content based on predefined or custom code.

Usage

get_archives_link( $url, $text, $format = 'html', $before = '', $after = '', $selected = false );

Parameters

  • $url (string) – Required. URL to the archive.
  • $text (string) – Required. Archive text description.
  • $format (string) – Optional. Can be ‘link’, ‘option’, ‘html’, or custom. Default ‘html’.
  • $before (string) – Optional. Content to prepend to the description. Default: ”.
  • $after (string) – Optional. Content to append to the description. Default: ”.
  • $selected (bool) – Optional. Set to true if the current page is the selected archive page. Default: false.

More information

See WordPress Developer Resources: get_archives_link()

Examples

This example retrieves and displays archive links in an unordered list.

$archives = wp_get_archives( array( 'echo' => 0 ) );
echo '<ul>' . $archives . '</ul>';

This example retrieves archive links and displays them in a dropdown menu.

$archives = wp_get_archives( array( 'echo' => 0, 'format' => 'option' ) );
echo '<select onchange="document.location.href=this.options[this.selectedIndex].value;">' . $archives . '</select>';

This example adds a custom CSS class to the archive links.

function custom_archive_links( $link_html ) {
    $link_html = str_replace( '<a', '<a class="my-custom-class"', $link_html );
    return $link_html;
}
add_filter( 'get_archives_link', 'custom_archive_links' );

This example retrieves archive links and displays them with custom content before and after the link.

$archives = wp_get_archives( array( 'echo' => 0, 'before' => '<strong>', 'after' => '</strong>' ) );
echo '<ul>' . $archives . '</ul>';

Highlight the current archive page

This example highlights the current archive page by adding a custom CSS class to the active link.

function highlight_current_archive( $link_html, $url, $text, $format, $before, $after ) {
    if ( is_archive() && get_the_permalink() == $url ) {
        $link_html = str_replace( '<a', '<a class="active-archive"', $link_html );
    }
    return $link_html;
}
add_filter( 'get_archives_link', 'highlight_current_archive', 10, 6 );