获取WordPress文章的第一个链接

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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/

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号