「一个人的桃花源」

文章最后更新时间为:2021 年 02 月 15 日 15:56:33

不用插件实现在任意一个页面被访问时,利用API接口向百度推送/提交该页面链接。特点:

  • 可以保证每天每个链接只被推送一次,防止超出API接口调用次数限制。
  • 无需在站长工具里绑定主体。
  • 访问页面自动推送。
  • 404页面和Search页面不推送。

使用方法

function.php中添加如下代码(将代码中的$api设为自己的接口调用地址即可):

/**
 * 百度SEO
 */

function auto_push_to_baidu($now, $options) {
    if(http_response_code()==404) return;
    if($now->is('search')) return;
    $now_url = $now->request->getPathInfo();
    $db      = Typecho_Db::get();
    $com_url = substr($options->siteUrl, 0, -1) . $now_url;
    try {
        $all = $db->fetchAll($db->select()->from('table.seo'));
    } catch (Exception $e) {
        $db->query('CREATE TABLE `test`.`typecho_seo` ( `seo_date` DATE NULL DEFAULT NULL , `website_url` VARCHAR(200) NULL DEFAULT NULL ) ENGINE = InnoDB;');
    }
    date_default_timezone_set("PRC");
    $insert  = $db->insert('table.seo')->rows(array('website_url' => $now_url, 'seo_date' => date('Y-m-d')));
    $row = $db->fetchRow($db->select()->from('table.seo')->where('website_url = ?', $now_url));
    $urls = array($com_url);
    $api = 'http://data.zz.baidu.com/urls?site=https://vixbob.moe&token=6v2Q4aB3CF2HNOhM';
      // 需替换为自己的接口调用地址
    $ch = curl_init();
    $options =  array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    if(count($row) == 0) {
        $db->query($insert);
        $result = curl_exec($ch);
    } else if($row['seo_date'] != date('Y-m-d')) {
        $result = curl_exec($ch);
        $db->query($db->update('table.seo')->rows(array('seo_date' => date('Y-m-d')))->where('website_url = ?', $now_url));
    }
}

并在footer.php或者hearder.php中合适的位置添加如下代码:

<?php auto_push_to_baidu($this, $this->options); ?>

例如在footer.php中添加代码:

接口调用地址如图:

实现方法

利用$this->options->siteUrl获取站点链接,$this->request->getPathInfo()获取链接后缀并作为网页唯一标识。

在数据库中记录每个页面的最后推送时间,如果和当前时间不同则推送,否则表明已经推送过了。

一些问题

当我直接将$this传入函数后,$this->options会变成NULL,也就是说在auto_push_to_baidu$now->options->siteUrl无法访问。但是将$this->options作为参数传递则可以访问$siteUrl。目前原因不明。求助PHP神仙。

标签: Typecho, 百度SEO, 博客优化

仅有一条评论

  1. 現在好像會顯示DatabaseQueryErro
    不知道是甚麼原因

添加新评论

Hitokoto

分类

归档

友情链接

其它