自从百度宣布将会把80%引流给优质熊掌号后,所以很多的站长朋友也想让站点接入百度熊掌号,以便百度熊掌号对原创文章的收录和搜索结果以及熊掌号页面的展现效果,下面就把WordPress实现熊掌号H5页面结构化改造过程及代码分享给大家。
首先我们需要根据百度熊掌号后台的“页面改造”里的提示先给自己的站点做个小小的改造以便百度熊掌号可以快速的识别和运用我们站点的链接数据,比如搜索结果中以结构化样式展现等。
页面改造最重要的其实就是添加 JSON_LD 数据了,其实可以用下面的代码来实现:
- //获取文章/页面摘要
- 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;
- }
以上两段代码添加到你需要接入熊掌号的主题的 functions.php 中
- <?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的合适的位置
相关