How to filter to output of the get_permalink() function

Note that post_link filter is only for the post post type.

For other post types these filters are available:

The get_permalink()function is actually a wrapper for:

  • get_post_permalink()
  • get_attachement_link()
  • get_page_link()

in those cases.

Here’s a way (untested) to create a custom wpse_link filter for all the above cases of get_permalink():

foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type )
{
    add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type )
    {
        return apply_filters( 'wpse_link', $url, $post_id, $sample, $type );
    }, 9999, 3 );
}

where we can now filter all cases with:

add_filter( 'wpse_link', function(  $url, $post_id, $sample, $type )
{
    return $url;
}, 10, 4 );

Leave a Comment