I want to grab the first link in a post and display it in an excerpt. This is going into a free theme which will be released at a later date and supports post formats (tumblog) - if you want to know when it launches just add me on twitter @lucaswynne
<strong>Question 1</strong>
I need a clean (compact as possible) PHP code I can use to call up the first link from a post and display it in the excerpt
- If the first link is <a href="http://www.facebook.com">Facebook</a> I want it to call it up as a link that says Facebook, not one that shows the entire url
- Make sure to add the ability to add a class to this link please!
- Unless WP supports this already and I'm oblivious to it please provide me both with what to post in functions and the PHP code to call it.
Thank ya.
Loveleen Kaur answers:
You can extract the first link from the content using php.
<?php
$testcontent=get_the_content();
$regex = '/(<a\s*'; // Start of anchor tag
$regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
$regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
$regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
$regex .= '(?P<name>\S+)'; // Grab the name
$regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)
preg_match($regex, $texttest, $matches);
echo '<a href="'.$matches['link'].'" class="'.$myclass.'">'.$matches['name'].'</a>';
?>
Lucas Wynne comments:
Unless there's a different way to implement this, it does not work.
Lawrence Krubner answers:
As a rule, I never post answers here, and I certainly don't want anyone to send any money to me, but I did ask almost the same question awhile back:
[[LINK href="http://www.wpquestions.com/question/show/id/873"]]http://www.wpquestions.com/question/show/id/873[[/LINK]]
[[LINK href="http://larkisadora.com/web.html"]]The designer who built my personal weblog[[/LINK]] used this code, as you can see:
[[LINK href="http://www.smashcompany.com/"]]http://www.smashcompany.com/[[/LINK]]
If this info is at all useful to you, you can let the money go to the Community Pot.
alchemist alchemist answers:
You can probably use something like this :
<?php $page_id = 238; //your page id should replace 238
$page = get_page($page_id); // get page details
$x = $page->post_content; // get page content
if(preg_match('/<a href=\'(.*?)\'>(.*?)<\/a>/i',$x,$matches)){
echo $matches[0];
// $matches[0] will contain your entire link in the format <a href='link_url_here'>This is the link</a>
}
?>