Overwrite Default Post Permalinks

Every WordPress post has a permalink by default. The permalink is displayed, as expected, by the the_permalink() function. In some cases, we might need to enforce another URL to a post as its permalink, be it another link within the site or an external URL. We can provide the custom URL through a custom field that we will conveniently name overwrite_permalink.

Before you think of polluting your theme files with those nasty conditionals, think again. What we will be using to achieve this is a custom function that we are going to hook into WordPress through the the_permalink and the the_permalink_rss filters. The first one will take care of the user-facing website and the other will handle RSS readers, so that we can have a consistent experience everywhere. This filters allow us to make the change in just once place, instead of making a mess of all our theme files.

Check the end result below:

function ns_overwrite_permalink($permalink)
    if( $custom = get_post_meta(get_the_ID(), 'overwrite_permalink', true) ) {
        $permalink = $custom;
    return $permalink;
add_filter('the_permalink', 'ns_overwrite_permalink');
add_filter('the_permalink_rss', 'ns_overwrite_permalink');

This code goes into the functions.php file and no other change is needed anywhere. Such is the power of WordPress hooks, so learn to leverage them.