WordPress tip: How to get the first link in posts

The first thing to do is to integrate the function to your theme. To do so, paste this code into your functions.php file.

function get_content_link( $content = false, $echo = false ){
    if ( $content === false )
        $content = get_the_content(); 

    $content = preg_match_all( '/hrefs*=s*["']([^"']+)/', $content, $links );
    $content = $links[1][0];

    if ( empty($content) ) {
    	$content = false;
    }

    return $content;
}

The function above finds the first link in the post and returns it for you. In this way, you can link the title(or whatever) to this place, as demonstrated below:

<h2><a href="<?php echo get_content_link( get_the_content() ); ?>"><?php the_title(); ?></a></h2>

Thanks to WP Snippets for the snippet!

Leave a Reply

Your email address will not be published. Required fields are marked *