Using WordPress ‘page_link’ PHP filter

The page_link WordPress PHP filter modifies the permalink for a specific page.

Usage

add_filter('page_link', 'my_custom_page_link', 10, 3);

function my_custom_page_link($link, $post_id, $sample) {
    // Your custom code here

    return $link;
}

Parameters

  • $link (string): The page’s current permalink.
  • $post_id (int): The ID of the page.
  • $sample (bool): Indicates if it’s a sample permalink.

More information

See WordPress Developer Resources: page_link

Examples

This code appends a custom query string to the page permalink.

add_filter('page_link', 'append_query_string', 10, 3);

function append_query_string($link, $post_id, $sample) {
    $link = add_query_arg('custom_key', 'custom_value', $link);
    return $link;
}

This code adds a language code to the permalink of a page based on a custom field.

add_filter('page_link', 'add_language_code', 10, 3);

function add_language_code($link, $post_id, $sample) {
    $language_code = get_post_meta($post_id, 'language_code', true);
    if ($language_code) {
        $link = home_url("/$language_code") . $link;
    }
    return $link;
}

This code removes the parent page slug from a child page’s permalink.

add_filter('page_link', 'remove_parent_slug', 10, 3);

function remove_parent_slug($link, $post_id, $sample) {
    $post = get_post($post_id);
    if ($post->post_parent) {
        $link = str_replace(get_permalink($post->post_parent), '', $link);
    }
    return $link;
}

Change permalink structure for a custom post type

This code changes the permalink structure for a custom post type called “product”.

add_filter('page_link', 'change_product_permalink', 10, 3);

function change_product_permalink($link, $post_id, $sample) {
    $post = get_post($post_id);
    if ($post->post_type == 'product') {
        $link = home_url("/products/{$post->post_name}");
    }
    return $link;
}

This code adds a custom prefix to the permalink.

add_filter('page_link', 'add_custom_prefix', 10, 3);

function add_custom_prefix($link, $post_id, $sample) {
    $link = str_replace(home_url(), home_url('/custom-prefix'), $link);
    return $link;
}