Using WordPress ‘post_type_archive_link’ PHP filter

The post_type_archive_link WordPress PHP filter allows you to modify the permalink of a post type archive.

Usage

add_filter('post_type_archive_link', 'my_custom_function', 10, 2);

function my_custom_function($link, $post_type) {
    // your custom code here
    return $link;
}

Parameters

  • $link (string) – The post type archive permalink.
  • $post_type (string) – Post type name.

More information

See WordPress Developer Resources: post_type_archive_link

Examples

Change archive link for a custom post type

Modify the archive link for a custom post type named ‘events’.

add_filter('post_type_archive_link', 'change_events_archive_link', 10, 2);

function change_events_archive_link($link, $post_type) {
    if ('events' == $post_type) {
        $link = home_url('/custom-events-archive/');
    }
    return $link;
}

Add the year and month query parameters to the archive link.

add_filter('post_type_archive_link', 'add_year_month_query_params', 10, 2);

function add_year_month_query_params($link, $post_type) {
    $year = date('Y');
    $month = date('m');
    $link = add_query_arg(array('year' => $year, 'month' => $month), $link);
    return $link;
}

Remove the trailing slash from the post type archive link.

add_filter('post_type_archive_link', 'remove_trailing_slash', 10, 2);

function remove_trailing_slash($link, $post_type) {
    return untrailingslashit($link);
}

Add a language parameter to the post type archive link for a multilingual site.

add_filter('post_type_archive_link', 'add_language_param', 10, 2);

function add_language_param($link, $post_type) {
    $language = 'en';
    $link = add_query_arg('lang', $language, $link);
    return $link;
}

Change the post type archive link based on the current user’s role.

add_filter('post_type_archive_link', 'change_link_based_on_user_role', 10, 2);

function change_link_based_on_user_role($link, $post_type) {
    if (current_user_can('administrator')) {
        $link = home_url('/admin-archive/');
    }
    return $link;
}