代码实现WordPress站点添加百度是否收录功能

494次阅读
没有评论

共计 1493 个字符,预计需要花费 4 分钟才能阅读完成。

最近看到很多站点上有一个百度是否收录的按钮,就搜索了一下相关代码,在自己的主题上进行了修改。

代码实现 WordPress 站点添加百度是否收录功能

修改的文件主要有两个 functions.php 与 single.php,在修改之前备份一下文件,以防止因操作不当引起的种种问题。

functions.php 文件修改

首先将一下代码添加到你主题的 functions.php 文件中,部分主题可能禁止编辑这个文件,不过一般主题作者应该会提供另一个文件方便大家对主题的修改,比如 functions_z.php。

/**
 * WordPress 添加百度是否收录功能
**/
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 文件修改

single.php 文件是主题的文章页面,一般我们将这个功能添加到这里可以方便访客实时查看到此篇文章是否被百度收录,你可以将下面的短代码添加至你希望放置的位置。

<?php baidu_record(); ?>

目前对于我使用的 DUX 主题,我是将这段代码添加到了如下位置,大家可做参考。

<span class="item"><?php echo _get_post_comments() ?></span>
<span class="item"><?php baidu_record(); ?></span>
<span class="item"><?php edit_post_link('[编辑]'); ?></span>

效果看图

代码实现 WordPress 站点添加百度是否收录功能

 

主要代码来自: 蝈蝈要安静的博客

正文完
 0
水东柳
版权声明:本站原创文章,由 水东柳 于2019-05-13发表,共计1493字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)