获取WordPress文章的第一个链接

时间:2019-08-29   阅读:493

WordPress文章格式中有一种是链接,用来快速分享一个链接,如果我们可以将文章的这个链接自动链接到这篇文章的标题中,远比在文章内容中直接显示这个链接来的完美。将下面的代码添加到当前主题的 functions.php 中:

1
2
3
4
5
6
7
8
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;
}

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

然后你可以类似下面的代码来为标题添加这个链接:

1
2
3
<h2><a href="<?php echo get_content_link( get_the_content() ); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>">Comment »</a>

<h2><a href="<?php echo get_content_link( get_the_content() ); ?>"><?php the_title(); ?></a></h2> <p><?php the_excerpt(); ?></p> <a href="<?php the_permalink(); ?>">Comment »</a>

参考资料:http://wp-snippets.com/get-the-first-link-in-post/

上一篇:将WordPress的作者存档链接重定向到about页面

下一篇:让WordPress分类/标签等存档页也能置顶文章

网友评论