百度普通收录API其实和昨天我制作了个神马站长平台MIP数据提交功能很像,所以今天分享把百度普通收录API加入到WordPress中。
在WordPress主题文件functions.php
中或者使用Code Snippets插件添加自定义代码:
add_action( 'publish_post', function( $post_id ) { if ( wp_is_post_revision( $post_id ) || get_post_status( $post_id ) != 'publish' ) { return; } $post = get_post( $post_id ); if ( $post->post_type === 'post' ) { $token = ''; // 在搜索资源平台申请的推送用的准入密钥(token)。 $urls = array( get_permalink( $post_id ), ); // $admin_email = get_option( 'admin_email' ); $admin_email = '[email protected]'; // 换成你的邮箱,或者使用管理员 邮箱get_option( 'admin_email' ) $api = 'http://data.zz.baidu.com/urls?site=https://wpmore.cn&token=' . $token; // 记得换你的域名 $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 ); $result = curl_exec( $ch ); // get returnCode $returnCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); // result to string $result = (string) $result; // send email $subject = ''; if ( $returnCode === 200 ) { $subject = '百度资源普通收录API提交成功'; } else { $subject = '百度资源普通收录API提交失败'; } $message = '<p>' . get_the_title( $post_id ) . '</p><p>' . implode( '\n', $urls ) . '</p>'; $message .= '<p>' . $result . '</p>'; $headers = array( 'Content-Type: text/html; charset=UTF-8', 'From: ' . $admin_email, ); wp_mail( $admin_email, $subject, $message, $headers ); curl_close( $ch ); } }, 10, 2 );
完成之后,在发布文章时,就会像邮箱推送邮件是否API提交成功。