Filtering links using the WordPress ‘the_permalink’ filter

by Landon | Jun 06, 2017 | Leave a comment

This morning I improved this theme by adding a filter to WordPress’s ‘the_permalink’ filter. The idea was to scan post content, pull out the first link in a post and then use that link as the permalink, so to speak. By doing this, I make it so that I can simply point my readers to other posts that I find particularly meaningful without them having to click onto an additional page.

Here’s my filter function, plus a few links for reference…

function elegance_first_link_in_link_posts($url){
    global $post;
    if(get_post_format($post->ID) !== 'link') return $url;
    $content_to_parse = apply_filters('the_content', $post->post_content);
    $dom = new DOMDocument;
    $dom->loadHTML($content_to_parse);
    $anchors = $dom->getElementsByTagName('a');
    if($anchors->length <= 0) return $url;
    return $anchors->item(0)->getAttribute('href');
}
add_filter('the_permalink', 'elegance_first_link_in_link_posts');

PHP DOMDocument documentation

WordPress ‘the_permalink’ filter