Snow's Blog
记录朝花夕拾的日子

WordPress 熊掌号 JSON-LD 结构化数据页面改造代码

WordPress 百度熊掌号 Json_LD 数据完整代码

经过多次摸索与网上参考资料,终于把网页改造成百度要求的H5页面。
其实改造也很简单,就是把如下两段代码放到需要改造模板的function.php和header.php的合适区域即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//获取文章/页面摘要
function fanly_excerpt($len=220){
	if ( is_single() || is_page() ){
		global $post;
		if ($post->post_excerpt) {
			$excerpt  = $post->post_excerpt;
		} else {
			if(preg_match('/<p>(.*)<\/p>/iU',trim(strip_tags($post->post_content,"<p>")),$result)){
				$post_content = $result['1'];
			} else {
				$post_content_r = explode("\n",trim(strip_tags($post->post_content)));
				$post_content = $post_content_r['0'];
			}
			$excerpt = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,0}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s','$1',$post_content);
		}
		return str_replace(array("\r\n", "\r", "\n"), "", $excerpt);
	}
}
 
//获取文章中的图 last update 2018/01/22
function fanly_post_imgs(){
	global $post;
	$src = '';
	$content = $post->post_content;  
	preg_match_all('/<img .*?src=[\"|\'](.+?)[\"|\'].*?>/', $content, $strResult, PREG_PATTERN_ORDER);  
	$n = count($strResult[1]);  
	if($n >= 3){
		$src = $strResult[1][0].'","'.$strResult[1][1].'","'.$strResult[1][2];
	}elseif($n >= 1){
		$src = $strResult[1][0];
	}
	return $src;
}

把以上代码添加到wordpress主题的 functions.php 中,然后继续:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
if(is_single()){
	echo '<script type="application/ld+json">{
	"@context": "https://ziyuan.baidu.com/contexts/cambrian.jsonld",
	"@id": "'.get_the_permalink().'",
 	"appid": "这里请填写熊掌号 ID",
	"title": "'.get_the_title().'",
	"images": ["'.fanly_post_imgs().'"],
	"description": "'.fanly_excerpt().'",
	"pubDate": "'.get_the_time('Y-m-d\TH:i:s').'"
}</script>
';}
?>

最后把以上这段代码添加在你的 WordPress 主题的 header.php 的合适的位置(注:该段代码在文章中输出)。

写在最后

关于 WordPress 接入百度熊掌号的 Json_LD 数据代码改造就给大家分享到这里了吧,如有问题请留言。(代码收集于网络,如有侵权请告知)

赞(1) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《WordPress 熊掌号 JSON-LD 结构化数据页面改造代码》
文章链接:https://www.snowing.cc/99.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 1

评论前必须登录!

 

  1. #1

    虽然看不懂代码,但感觉很高大上,赞一个?

    小雨6年前 (2018-07-02)

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册