WordPress获取文章中的第一个链接

我们知道 WordPress 日志格式(Post format)中有个 link 的格式,如果你的主题启用了 Post format 功能并且使用了 Link 这个格式,那么你想这篇日志直接链接到日志中的第一个链接。

function get_content_first_link( $content = false, $echo = false ){
if ( $content === false )
$content = get_the_content();

preg_match_all('/<a.*?href=[\'"](.*?)[\'"].*?>/i', $content, $links);

if($links){
return $links[1][0];
}else {
return false;
}
}


 

将上面的代码复制到当前主题的 functions.php,然后试用下面的方式引用:

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

 


下面是另外一种方法:

[WordPress]获取文章中的第一个链接

直接将下面代码添加到主题的functions.php文件中。

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;
}

$content : 文章内容

 

米粒在线
  • 本文由 发表于 2013年3月16日12:22:13
  • 转载请务必保留本文链接:https://www.miliol.org/4430.html
科技

无良运营商劫持网页:教你干掉小窗、非法广告

在中国,网页劫持可谓是非常常见的现象。上网看着看着,突然就能被传送到不知所谓的页面,铺满各种“屠龙宝刀点击就送”、“充值XX元就可获得流量大礼包”之类的内容。就算不是页面跳转,网页也有可能被插入额外的...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

评论:1   其中:访客  1   博主  0
    • tenda tenda 1

      你好,用了第一個之後
      會出現Fatal error: Call to undefined function get_content_link() in
      這個會挑WP主題嗎?