Filtering the Post Link

There have been a number of occasions when I’ve wanted to write posts but have them link to another site rather than the post on the WordPress site. It happened most recently with media coverage for a research project.

It didn’t seem worth building a whole custom post type for the media coverage. Instead I was adding using Advanced Custom Fields to add a field for an external URL when the post was put in the News category.

Initially, I built the post creation to look and see if that field had content then use it instead of the permalink. It looked something like this.

if (get_field('media_url', $post_id)){
			$link = get_field('media_url', $post_id);
		} else {
			$link = get_the_permalink();
		}

It was fine. A bit messy but fine. One way if failed was in the “read more” links which still had the original permalink. Now I could have built out a custom read more link but that seemed needlessly complex.

Instead, I looked a round a bit for a WP filter to use on the permalink and found post_link. That enabled me to do the following. Nice and easy and it applies to the read more links too.

function divh_news_permalink_filter($url, $post) {
    $post_id = $post->ID;
    if(get_field('media_url', $post_id)){
        $media_url = get_field('media_url', $post_id);
        return $media_url;
    } else {
        return $url;
    }
}
add_filter('post_link', 'divh_news_permalink_filter', 10, 2);    

Leave a Reply