FUNCTIONS.PHP
// Extract first occurance of text from a string
if( !function_exists ('extract_from_string') ) :
function extract_from_string($start, $end, $tring) {
$tring = stristr($tring, $start);
$trimmed = stristr($tring, $end);
return substr($tring, strlen($start), -strlen($trimmed));
}
endif;
FORMAT-LINK.PHP
// Get the text & url from the first link in the content
$content = get_the_content();
$link_string = extract_from_string('<a href=', '/a>', $content);
$link_bits = explode('"', $link_string);
foreach( $link_bits as $bit ) {
if( substr($bit, 0, 1) == '>') $link_text = substr($bit, 1, strlen($bit)-2);
if( substr($bit, 0, 4) == 'http') $link_url = $bit;
}?>
<h2 class="post-title"><a href="<?php echo $link_url;?>" title="<?php _e('External link');?>"><?php echo $link_text;?></a></h2>
@esmi Thanks for the code!
But I’m not quite clear how to use the format-link.php
I created a file named format-link.php
in my theme directory, but nothing happens.
I tried paste the code into loop, error occurs.
What should I do?
What Theme are you using?
Your Theme needs to enable support for Post Formats, including explicitly declaring the Post Format types it will support.
Then, the Theme needs to include custom layout/style for each given Post Format type.
@chip Bennett
It’s a child theme of twentyten.
I have add link
to add_theme_support()
Then I tried adding
`if ( has_post_format( ‘link’ )) {
echo ‘this is the link format’;
}`
into loop and it worked.
Since I’m not able to figure out how to use the code @esmi has provided, I tried to study the php function in his code,stristr()
,substr()
,strlen()
(I know really very little about coding), and finally I came up with some code, they work fine with the purpose what I have originally described–extract the first link from content, or we just put a plain url in content, and the output become the post title linking to the address.
Just put the code in loop, and nothing has to be add into functions.php
[Code moderated as per the Forum Rules. Please use the pastebin]
Since I’m not a php guy, the code is much likely to fail in some case. But as I haven’t yet found an easy way to achieve this on the internet, I just paste them here and hope some veteran would give further advice.