现在这样的插件不少,但是都大同小异,你抄袭我,我再抄袭他!
所以就打算自己来整一下!代码基于wordpress自带的WP_Http,实现了新发布文章和更新文章的功能,同时使用wordpress内置的消息提示!
复制如下代码,替换成自己的token。
token可以在这里找到:https://ziyuan.baidu.com/linksubmit/index
function post_handle( $url, $types ){
$WEB_TOKEN = 'token'; //这里请换成你的网站的百度主动推送的token值
$WEB_DOMAIN = get_option('home');
$api = 'http://data.zz.baidu.com/urls?site='.$WEB_DOMAIN.'&token='.$WEB_TOKEN;
if ($types == 'update') {
$api = 'http://data.zz.baidu.com/update?site='.$WEB_DOMAIN.'&token='.$WEB_TOKEN;
}
$request = new WP_Http;
$result = $request->request( $api , array( 'method' => 'POST', 'body' => $url , 'headers' => 'Content-Type: text/plain') );
$result = json_decode($result['body'] , true);
if (array_key_exists('success' , $result )) {
set_transient('has_post_submitBaidu' , 'yes' );
}elseif ($types == 'update' && array_key_exists('success' , $result )) {
set_transient('has_post_updateBaidu' , 'yes' );
}
}
// submit to Baidu
if(!function_exists('Baidu_Submit')){
add_action('publish_post', 'Baidu_Submit', 0);
function Baidu_Submit($post_ID) {
$url = get_permalink($post_ID);
post_handle( $url, 'submit');
}
}
// update to Baidu
if (!function_exists('Baidu_Update')) {
add_action('post_updated', 'Baidu_Update',0);
function Baidu_Update($post_ID) {
$url = get_permalink($post_ID);
post_handle( $url, 'update');
}
}
// 显示提交到百度的消息
add_action('admin_notices', 'submit_admin_notice');
function submit_admin_notice(){
$class = 'notice notice-success is-dismissible';
$newmessage = __('成功提交到百度站长平台.');
$updatemessage = __('成功更新到百度站长平台.');
if ( get_transient( 'has_post_submitBaidu' ) == 'yes' ) {
printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $newmessage ));
delete_transient( 'has_post_submitBaidu' );
}elseif (get_transient( 'has_post_updateBaidu' ) == 'yes') {
printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $updatemessage ));
delete_transient( 'has_post_updateBaidu' );
}
}
文章评论