WordPress获取日志头一个链接方法

追格官方小助手/ 2022年04月07日/ WordPress/ 浏览 1200

WordPress主题若启用了Post format 功能并使用了Link这个格式,我们若想该日志直链到日志中的头一个链接应该怎么操作?


将下面代码放到当前WordPress模板functions.php文件内即可。


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


然后在相应页面调用下面代码即可:


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


发表评论

暂无评论,抢个沙发...

客服 工单