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

wordpress主题 网站建设1 3,434阅读模式

我们知道 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
百科知道

网站速度很慢?使用 WordPress 短时缓存(Transients)来优化数据库查询和 HTTP 响应!

每个人都想要一个速度很快的网站,网站速度越快,用户停留和点击页面或购买产品的时间就越长,加快网站速度的方法之一是开启缓存,而缓存背后的逻辑就是存储信息,更具体一点说,就是找到一个比连接数据库更快的存储...
    • tenda 1

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

    发表评论

    匿名网友
    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
    确定

    拖动滑块以完成验证