原标题:WordPress添加熊掌号JSON_LD数据结构(亲测有用)
今天弄了下熊掌号,因为我的代码水平一般,费了半天劲也没有弄对,看到网上的教程实测成功了,就分享出来,在这里感谢泪雪大神。
首先要明确的是,百度给的JSON_LD数据代码,只是一串js,不能识别具体的信息,所以要加入WordPress必须要进行变量的处理,这是官方的源代码:
< type=”application/ld+json”>
{
“@context”: “https://ziyuan.baidu.com/contexts/cambrian.jsonld”,
“@id”: “https://ziyuan.baidu.com/college/articleinfo?id=1464”,
“appid”: “1559401964951871”,
“title”: “百度移动搜索落地页体验白皮书——广告篇2.0”,
“images”: [
“https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png”,
“https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png”,
“https://m.baidu.com/static/index/plus/plus_logo.png”
],
“deion”: “优质合理的广告作为信息的补充,广受用户喜欢。2017年初百度用户体验部针对用户进行了满意度调研,发现很多恶意低质的广告严重破坏着用户的搜索体验。”,
“pubDate”: “2017-06-15T08:00:01”,
“upDate”: “2017-06-16T01:02:03”,
“lrDate”: “2017-06-17T09:10:11”
}
>
这串代码是要加在文章页面里的,但是考虑到WordPress的公共头部属性,我们在添加的时候要进行if判断,也就是说当遇到文章页面,header才要加载这串js,下面是具体步骤:
首先,将如下判断加入 functions.php
//获取文章/页面摘要
function fanly_excerpt($len=220){
if ( is_single() || is_page() ){
global $post;
if ($post->post_excerpt) {
$excerpt = $post->post_excerpt;
} else {
if(preg_match(‘/
(.*)/iU’,trim(strip_tags($post->post_content,”
”)),$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(‘//’, $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的header文件的head区域内:
if(is_single()){
echo ‘< 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().'”],
“deion”: “‘.fanly_excerpt().'”,
“pubDate”: “‘.get_the_time(‘Y-m-d\TH:i:s’).'”
}>
‘;}
?>
大家可以看到,上面的代码进行了if判断,意思是只有遇到的了文章页才会加载这个头部。
最后,对代码进行在线检测,这个在站在工具后台就可以检测到: