Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How to grab the first link in a post WordPress

  • SOLVED

[[LINK href="http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it"]]I am intrigued by the code here:[[/LINK]]

function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}



How would I modify the regex to pull out the first link in a post? I want to pull out the first link and establish that in a special place in the template.


Answers (4)

2010-09-13

Maor Barazany answers:

Try this one:


<?php
function catch_that_link() {
global $post, $posts;
$first_link = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<a[\s]+[^>]*?href[\s]?=[\s\"\']+(.*?)[\"\']+.*?>([^<]+|.*?)?<\/a>/is', $post->post_content, $matches);

$first_link = $matches [1] [0];
if(empty($first_link)){ //Defines a default link
$first_link = "<a href='http://www.some_default_link.com'>link text</a>";
}
return $first_link;
}
?>


Then to print this link you use the function:


<?php echo $first_link = catch_that_link(); ?>

2010-09-13

Darrin Boutote answers:

function catch_that_link() {
global $post, $posts;
ob_start();
ob_end_clean();
$output = preg_match_all('/<a[^>]*>(.*?)<\/a>/i', $post->post_content, $matches);

$first_link = $matches[0][0];

return $first_link;

}

echo catch_that_link();

2010-09-14

Ashfame answers:

I would suggest using HTML DOM parser - http://sourceforge.net/projects/simplehtmldom/

Its very easy and can do all the heavy lifting for you and much more things.

Here is how to work with it :


// Load the HTML DOM Parser Library
require_once('simple_html_dom.php');

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br />';

// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br />';

2010-09-14

enodekciw answers:

Ok, the most simple solution, imo.

Paste this code into your functions.php:

function get_first_link() {
global $post, $posts;
preg_match_all('/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $links);
return $links[1][0];

}

That preg match should extract only URL (not the whole <a href="www.example.com">example</a>, but only www.example.com).

So, how to use it?


<?php $first_link = get_first_link(); ?>
<a href="<?php echo $first_link; ?>" title="First link in <?php the_title(); ?> post">This is first link in <?php the_title(); ?></a>


So, basically you get the URL of the first link in post and then you can use it as you wish ;) just echo it out using <?php echo $first_link; ?>