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 数据代码改造就给大家分享到这里了吧,如有问题请留言。(代码收集于网络,如有侵权请告知)
虽然看不懂代码,但感觉很高大上,赞一个?