Quantcast
Channel: WPRecipes
Viewing all articles
Browse latest Browse all 121

WordPress tip: How to get the first link in posts

$
0
0

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!


Viewing all articles
Browse latest Browse all 121

Trending Articles