WordPress给文章添加百度是否已收录的功能

2019年7月23日15:46:17 4 1,877 views

这个功能也是出来很久了,之前在其他网站上有看到过,一直想有这样的一个功能,到今天才找个时间把这个功能给添加起了,本文摘抄张戈博客https://zhang.ge/4617.html,原文也提供了相应的插件。

这个功能添加起来简单,首先编辑主题目录的functions.php文件,在最后一个?>前新增如下代码并保存:

/**
 * WordPress 显示百度是否收录功能(自定义栏目优化版)
 * https://zhang.ge/4617.html
 * DIY By 张戈博客 
**/
function baidu_check($url,$post_id){
    $baidu_record  = get_post_meta($post_id,'baidu_record',true);
    if( $baidu_record != 1){
        $url='http://www.baidu.com/s?wd='.$url;
        $curl=curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $rs=curl_exec($curl);
        curl_close($curl);
        if(!strpos($rs,'没有找到该URL。您可以直接访问') && !strpos($rs,'很抱歉,没有找到与') ){
            update_post_meta($post_id, 'baidu_record', 1) || add_post_meta($post_id, 'baidu_record', 1, true);
            return 1;
        } else {
            return 0;
        }
    } else {
       return 1;
    }
}
function baidu_record() {
    global $wpdb;
    $post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
    if(baidu_check(get_permalink($post_id), $post_id ) == 1) {
        echo '<a target="_blank" title="点击查看" rel="external nofollow" href="http://www.baidu.com/s?wd='.get_the_title().'">百度已收录</a>';
   } else {
        echo '<a style="color:red;" rel="external nofollow" title="点击提交,谢谢您!" target="_blank" href="http://zhanzhang.baidu.com/sitesubmit/index?sitename='.get_permalink().'">百度未收录</a>';
   }
}

第二步,编辑文章模板(一般是single.php,begin5.2是/template/content.php),在合适的位置添加如下代码并保存:如果是begin主题的话可以参考begin5.2文件目录详情

<?php baidu_record(); ?>

若以上步骤都未出错,那现在访问文章页面就能看到百度是否已收录的效果了。当然你要有兴趣还可以将这个代码继续添加到首页或分类页面。

第一次访问可能会有点卡,当数据库存在记录之后,将直接从数据库查询,而不会有任何拖慢速度感觉了!

 

历史上的今天:


欢迎来到菜鸟头头的个人博客
本文章百度已收录,若发现本站有任何侵犯您利益的内容,请及时邮件或留言联系,我会第一时间删除所有相关内容。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:4   其中:访客  3   博主  1

    • avatar 值得入手 1

      这个代码有点老了。应该更新一下百度的网址,百度的zhanzhang现在变成ziyuan了

      • avatar 奶爸建网站笔记 4

        我昨天刚去掉,因为我发现我把代码里面的网址改成https后就不准了。