WordPress熊掌号移动端页面改造最重要的其实就是添加 JSON_LD 数据了,其实可以用下面的代码来实现,大家把以下这段代码添加到你需要接入熊掌号的主题的 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('/<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;
- }
- //熊掌号h5页面改造
- function fanly_h5(){
- if(is_single()){
- echo '<link rel="canonical" href="'.get_the_permalink().'" />';
- 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>
- ';
- echo '<script src="//msite.baidu.com/sdk/c.js?appid=自己的熊掌号ID"></script>';
- }
- }
其中的【自己的熊掌号ID】,要改成自己网站的熊掌号ID。文章源自SEO视频网-https://www.seoshipin.cn/gongju/2788.html
最后大家在header.php中找到</head>标签,在</head>标签前面加上<?php fanly_h5(); ?>
文章源自SEO视频网-https://www.seoshipin.cn/gongju/2788.html
- <?php fanly_h5(); ?>
以上代码还做了一个 if 判断,只让该段代码在文章中输出。文章源自SEO视频网-https://www.seoshipin.cn/gongju/2788.html 文章源自SEO视频网-https://www.seoshipin.cn/gongju/2788.html
评论