Thursday, December 6, 2012

How to get the first link in wordpress posts

How to get the first link in wordpress posts

Please follow the code structure to get the first link from a post.


To make this happen just 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 above function finds the first link in the post and returns that link to you. So In this following way, we can link the title(or whatever) to this place, as describe below:

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

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off