需求分析
- 文章发布/更新时实时推送 URL 到百度站长 API
- 支持一键推送历史所有文章(站点地图模式)
- 后台配置:准入密钥、推送开关、日志查看
步骤 1:裸插件骨架
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
class BaiduSubmit_Plugin implements Typecho_Plugin_Interface {
public static function activate() {
// 挂载文章发布钩子
Typecho_Plugin::factory('Widget_Contents_Post_Edit')->finishPublish = array('BaiduSubmit_Plugin', 'pushUrl');
return '插件激活成功,请进入设置填写准入密钥';
}
public static function deactivate() { return '插件已禁用'; }
public static function config(Typecho_Widget_Helper_Form $form) {
$token = new Typecho_Widget_Helper_Form_Element_Text('token', NULL, '', _t('准入密钥'), '在百度站长平台获取');
$form->addInput($token);
$switch = new Typecho_Widget_Helper_Form_Element_Radio('enable', array('1'=>_t('开启'),'0'=>_t('关闭')), '1', _t('实时推送'));
$form->addInput($switch);
}
public static function personalConfig(Typecho_Widget_Helper_Form $form) {}
public static function render() {} // 占位
}
步骤 2:实现实时推送
public static function pushUrl($post) {
$options = Typecho_Widget::widget('Widget_Options');
$pluginOpts = $options->plugin('BaiduSubmit');
if (empty($pluginOpts->token) || $pluginOpts->enable != '1') return;
$url = $post->permalink;
$api = "https://data.zz.baidu.com/urls?site={$options->siteUrl}&token={$pluginOpts->token}";
$ch = curl_init($api);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $url,
CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
));
$result = curl_exec($ch);
curl_close($ch);
// 记录日志
self::log($url, $result);
}
步骤 3:后台“推送历史数据”按钮
public static function config(Typecho_Widget_Helper_Form $form) {
// ... 前面的 token、enable ...
$btn = new Typecho_Widget_Helper_Form_Element_Button('pushAll', _t('推送所有历史文章'));
$btn->input->setAttribute('onclick', "if(confirm('确定推送所有历史文章?')){location.href='?action=pushAll'}");
$form->addInput($btn);
}
// 在 activate 中处理 action
public static function activate() {
// ... 原有挂载 ...
if (isset($_GET['action']) && $_GET['action'] === 'pushAll') {
self::pushAllHistory();
}
}
public static function pushAllHistory() {
$db = Typecho_Db::get();
$rows = $db->fetchAll($db->select('permalink')->from('table.contents')->where('type = ?', 'post')->where('status = ?', 'publish'));
$urls = array_column($rows, 'permalink');
$chunks = array_chunk($urls, 100); // 百度单次最多 100 条
foreach ($chunks as $chunk) {
// 同 pushUrl 批量 POST
sleep(1); // 避免频率限制
}
echo '推送完成';
exit;
}
完善:日志记录与查看
private static function log($url, $result) {
$log = Typecho_Widget::widget('Widget_Options')->plugin('BaiduSubmit')->log ?? array();
$log[] = array('time'=>date('Y-m-d H:i:s'), 'url'=>$url, 'result'=>$result);
// 仅保留最近 100 条
if (count($log) > 100) array_shift($log);
// 存回配置(Typecho 无直接写配置 API,建议另建表或文件)
file_put_contents(__DIR__.'/push_log.json', json_encode($log));
}