WordPress 404死链自动提交到站长平台(防重复)

这是一个WordPress插件代码,用于自动将网站404死链接提交到各大搜索引擎站长平台。核心功能包括:检测404页面、获取当前URL、检查链接是否重复提交、支持百度、Google、Bing等平台,并记录提交历史到本地数据库。

文章作者:曾凤祥
阅读时间: 288 分钟
更新时间:2026年3月10日

完整解决方案

1. 核心功能文件(复制到主题的 functions.php

<?php
/**
 * WordPress 404死链接自动提交到站长平台
 * 支持:百度站长、Google Search Console、Bing Webmaster
 * 包含防重复提交和本地记录功能
 * 版本: 1.0.1
 */

if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * 自动检测并提交404死链接
 */
add_action( 'template_redirect', 'auto_submit_404_links' );
function auto_submit_404_links() {
    if ( is_404() && ! is_admin() ) {
        $current_url = get_current_url();
        
        // 检查是否已提交过
        if ( ! is_link_submitted( $current_url ) ) {
            // 提交到各站长平台
            submit_to_webmasters( $current_url );
            
            // 记录到本地数据库
            record_submitted_link( $current_url );
        }
    }
}

/**
 * 获取当前完整URL
 */
function get_current_url() {
    $protocol = ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $uri = $_SERVER['REQUEST_URI'];
    return $protocol . $host . $uri;
}

/**
 * 检查链接是否已提交过
 */
function is_link_submitted( $url ) {
    global $wpdb;
    
    // 检查数据库记录
    $table_name = $wpdb->prefix . '404_links_log';
    $result = $wpdb->get_var( 
        $wpdb->prepare( 
            "SELECT COUNT(*) FROM $table_name WHERE url = %s", 
            $url 
        ) 
    );
    
    if ( $result > 0 ) {
        return true;
    }
    
    // 检查选项记录
    $submitted_links = get_option( '404_submitted_links', array() );
    if ( in_array( md5( $url ), $submitted_links ) ) {
        return true;
    }
    
    return false;
}

/**
 * 提交到各站长平台
 */
function submit_to_webmasters( $url ) {
    $site_url = home_url();
    
    // 配置信息(请在后台设置)
    $webmaster_config = get_webmaster_config();
    
    // 1. 提交到百度站长平台
    if ( ! empty( $webmaster_config['baidu_token'] ) ) {
        submit_to_baidu( $url, $webmaster_config['baidu_token'], $site_url );
    }
    
    // 2. 提交到Google Search Console
    if ( ! empty( $webmaster_config['google_key_file'] ) ) {
        submit_to_google( $url, $webmaster_config['google_key_file'] );
    }
    
    // 3. 提交到Bing Webmaster Tools
    if ( ! empty( $webmaster_config['bing_api_key'] ) ) {
        submit_to_bing( $url, $webmaster_config['bing_api_key'] );
    }
    
    // 4. 提交到搜狗站长平台
    if ( ! empty( $webmaster_config['sogou_token'] ) ) {
        submit_to_sogou( $url, $webmaster_config['sogou_token'] );
    }
    
    // 触发钩子,方便其他插件扩展
    do_action( '404_link_submitted', $url );
}

/**
 * 提交到百度站长平台
 */
function submit_to_baidu( $url, $token, $site ) {
    $api_url = 'http://data.zz.baidu.com/urls?site=' . urlencode( $site ) . '&token=' . $token;
    
    $response = wp_remote_post( $api_url, array(
        'body'    => $url,
        'headers' => array(
            'Content-Type' => 'text/plain',
            'User-Agent'   => 'WordPress/404-Submitter',
        ),
    ) );
    
    if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
        $body = json_decode( wp_remote_retrieve_body( $response ), true );
        
        if ( isset( $body['success'] ) && $body['success'] > 0 ) {
            // 记录成功日志
            log_submission( 'baidu', $url, 'success', $body );
        } else {
            log_submission( 'baidu', $url, 'error', $body );
        }
    } else {
        log_submission( 'baidu', $url, 'error', wp_remote_retrieve_response_message( $response ) );
    }
}

/**
 * 提交到Google Search Console
 */
function submit_to_google( $url, $key_file_path ) {
    if ( ! file_exists( $key_file_path ) ) {
        log_submission( 'google', $url, 'error', 'Key file not found' );
        return;
    }
    
    // 这里需要Google API Client Library
    // 这是一个简化版本,实际使用需要安装Google API库
    $api_url = 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect';
    
    // 注意:实际实现需要OAuth2认证
    // 这里只提供概念代码
    log_submission( 'google', $url, 'info', 'Google submission requires OAuth2 setup' );
}

/**
 * 提交到Bing Webmaster Tools
 */
function submit_to_bing( $url, $api_key ) {
    $api_url = 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrl?apikey=' . $api_key;
    
    $data = array(
        'siteUrl' => home_url(),
        'url'     => $url,
    );
    
    $response = wp_remote_post( $api_url, array(
        'body'    => json_encode( $data ),
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
    ) );
    
    if ( ! is_wp_error( $response ) ) {
        $body = json_decode( wp_remote_retrieve_body( $response ), true );
        log_submission( 'bing', $url, 'success', $body );
    } else {
        log_submission( 'bing', $url, 'error', $response->get_error_message() );
    }
}

/**
 * 提交到搜狗站长平台
 */
function submit_to_sogou( $url, $token ) {
    $api_url = 'https://zhanzhang.sogou.com/api/submit?token=' . $token;
    
    $response = wp_remote_post( $api_url, array(
        'body'    => 'urls=' . urlencode( $url ),
        'headers' => array(
            'Content-Type' => 'application/x-www-form-urlencoded',
        ),
    ) );
    
    if ( ! is_wp_error( $response ) ) {
        $body = wp_remote_retrieve_body( $response );
        log_submission( 'sogou', $url, 'success', $body );
    } else {
        log_submission( 'sogou', $url, 'error', $response->get_error_message() );
    }
}

/**
 * 记录提交日志
 */
function log_submission( $platform, $url, $status, $response = '' ) {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_links_log';
    
    $wpdb->insert(
        $table_name,
        array(
            'platform'   => $platform,
            'url'        => $url,
            'status'     => $status,
            'response'   => is_array( $response ) ? json_encode( $response ) : $response,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
            'submitted_at' => current_time( 'mysql' ),
        ),
        array( '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
    );
}

/**
 * 记录已提交的链接
 */
function record_submitted_link( $url ) {
    global $wpdb;
    
    // 记录到数据库
    $table_name = $wpdb->prefix . '404_links_log';
    $wpdb->insert(
        $table_name,
        array(
            'platform'   => 'record',
            'url'        => $url,
            'status'     => 'recorded',
            'submitted_at' => current_time( 'mysql' ),
        ),
        array( '%s', '%s', '%s', '%s' )
    );
    
    // 同时记录到选项,用于快速检查
    $submitted_links = get_option( '404_submitted_links', array() );
    $submitted_links[] = md5( $url );
    
    // 只保留最近1000条记录
    if ( count( $submitted_links ) > 1000 ) {
        $submitted_links = array_slice( $submitted_links, -1000 );
    }
    
    update_option( '404_submitted_links', $submitted_links, false );
}

/**
 * 获取站长平台配置
 */
function get_webmaster_config() {
    return get_option( 'webmaster_404_config', array(
        'baidu_token'     => '',
        'bing_api_key'    => '',
        'sogou_token'     => '',
        'enable_baidu'    => false,
        'enable_bing'     => false,
        'enable_sogou'    => false,
        'google_key_file' => '',
    ) );
}

/**
 * 创建数据库表
 */
function create_404_links_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_links_log';
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        platform varchar(50) NOT NULL,
        url varchar(500) NOT NULL,
        status varchar(20) NOT NULL,
        response text,
        user_agent varchar(500),
        ip_address varchar(45),
        submitted_at datetime NOT NULL,
        PRIMARY KEY (id),
        KEY url_index (url(200)),
        KEY platform_index (platform),
        KEY submitted_at_index (submitted_at)
    ) $charset_collate;";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_404_links_table' );

/**
 * 清理旧记录(保留30天)
 */
function cleanup_old_404_records() {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_links_log';
    $days_ago = date( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
    
    $wpdb->query( 
        $wpdb->prepare( 
            "DELETE FROM $table_name WHERE submitted_at < %s", 
            $days_ago 
        ) 
    );
}
add_action( 'wp_scheduled_delete', 'cleanup_old_404_records' );
?>

2. 后台设置页面(复制到主题的functions.php)

<?php
/**
 * 站长平台配置页面
 */
add_action( 'admin_menu', 'register_404_submitter_menu' );
function register_404_submitter_menu() {
    add_menu_page(
        '404链接提交',
        '404提交',
        'manage_options',
        '404-link-submitter',
        'display_404_submitter_page',
        'dashicons-admin-links',
        30
    );
    
    add_submenu_page(
        '404-link-submitter',
        '提交日志',
        '提交日志',
        'manage_options',
        '404-submitter-logs',
        'display_submission_logs'
    );
    
    add_submenu_page(
        '404-link-submitter',
        '设置',
        '设置',
        'manage_options',
        '404-submitter-settings',
        'display_submitter_settings'
    );
}

/**
 * 显示设置页面
 */
function display_submitter_settings() {
    if ( isset( $_POST['submit_webmaster_settings'] ) && current_user_can( 'manage_options' ) ) {
        check_admin_referer( 'update_webmaster_settings' );
        
        $config = array(
            'enable_baidu'    => isset( $_POST['enable_baidu'] ),
            'baidu_token'     => sanitize_text_field( $_POST['baidu_token'] ),
            'enable_bing'     => isset( $_POST['enable_bing'] ),
            'bing_api_key'    => sanitize_text_field( $_POST['bing_api_key'] ),
            'enable_sogou'    => isset( $_POST['enable_sogou'] ),
            'sogou_token'     => sanitize_text_field( $_POST['sogou_token'] ),
            'google_key_file' => sanitize_text_field( $_POST['google_key_file'] ),
        );
        
        update_option( 'webmaster_404_config', $config );
        echo '<div class="notice notice-success"><p>设置已保存!</p></div>';
    }
    
    $config = get_webmaster_config();
    ?>
    <div class="wrap">
        <h1>404链接提交设置</h1>
        
        <form method="post" action="">
            <?php wp_nonce_field( 'update_webmaster_settings' ); ?>
            
            <table class="form-table">
                <!-- 百度站长平台设置 -->
                <tr>
                    <th scope="row">百度站长平台</th>
                    <td>
                        <label>
                            <input type="checkbox" name="enable_baidu" value="1" <?php checked( $config['enable_baidu'] ); ?>>
                            启用百度提交
                        </label>
                        <p class="description">获取方式:登录百度站长平台 → 普通收录 → 接口调用地址中的"token="参数</p>
                        <input type="text" name="baidu_token" value="<?php echo esc_attr( $config['baidu_token'] ); ?>" 
                               class="regular-text" placeholder="输入百度token">
                    </td>
                </tr>
                
                <!-- Bing Webmaster设置 -->
                <tr>
                    <th scope="row">Bing Webmaster</th>
                    <td>
                        <label>
                            <input type="checkbox" name="enable_bing" value="1" <?php checked( $config['enable_bing'] ); ?>>
                            启用Bing提交
                        </label>
                        <p class="description">获取方式:Bing Webmaster Tools → 配置我的网站 → API访问</p>
                        <input type="text" name="bing_api_key" value="<?php echo esc_attr( $config['bing_api_key'] ); ?>" 
                               class="regular-text" placeholder="输入Bing API Key">
                    </td>
                </tr>
                
                <!-- 搜狗站长平台 -->
                <tr>
                    <th scope="row">搜狗站长平台</th>
                    <td>
                        <label>
                            <input type="checkbox" name="enable_sogou" value="1" <?php checked( $config['enable_sogou'] ); ?>>
                            启用搜狗提交
                        </label>
                        <p class="description">获取方式:搜狗站长平台 → 链接提交 → Token</p>
                        <input type="text" name="sogou_token" value="<?php echo esc_attr( $config['sogou_token'] ); ?>" 
                               class="regular-text" placeholder="输入搜狗token">
                    </td>
                </tr>
                
                <!-- 其他设置 -->
                <tr>
                    <th scope="row">其他选项</th>
                    <td>
                        <label>
                            <input type="checkbox" name="log_404_requests" value="1" <?php checked( get_option( 'log_404_requests', false ) ); ?>>
                            记录所有404请求(仅记录,不提交)
                        </label>
                        <p class="description">记录所有404访问,用于分析网站死链情况</p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" name="submit_webmaster_settings" class="button button-primary" value="保存设置">
            </p>
        </form>
        
        <div class="card">
            <h3>使用说明</h3>
            <ol>
                <li>首先在相应的站长平台获取API密钥或Token</li>
                <li>勾选需要启用的平台并填写对应密钥</li>
                <li>保存设置后,系统会自动检测并提交404链接</li>
                <li>查看"提交日志"页面可以监控提交状态</li>
            </ol>
        </div>
    </div>
    
    <style>
    .form-table th { width: 200px; }
    .card { background: #fff; padding: 20px; margin-top: 20px; border-left: 4px solid #0073aa; }
    .card h3 { margin-top: 0; }
    .card ol { margin-left: 20px; }
    .description { color: #666; font-size: 12px; }
    </style>
    <?php
}

/**
 * 显示提交日志
 */
function display_submission_logs() {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_links_log';
    
    // 分页参数
    $per_page = 20;
    $current_page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
    $offset = ( $current_page - 1 ) * $per_page;
    
    // 获取总记录数
    $total = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
    
    // 获取日志
    $logs = $wpdb->get_results( 
        $wpdb->prepare( 
            "SELECT * FROM $table_name ORDER BY submitted_at DESC LIMIT %d OFFSET %d", 
            $per_page, 
            $offset 
        ) 
    );
    ?>
    <div class="wrap">
        <h1>404链接提交日志</h1>
        
        <div class="tablenav top">
            <div class="tablenav-pages">
                <?php
                $total_pages = ceil( $total / $per_page );
                if ( $total_pages > 1 ) {
                    echo paginate_links( array(
                        'base'     => add_query_arg( 'paged', '%#%' ),
                        'format'   => '',
                        'current'  => $current_page,
                        'total'    => $total_pages,
                        'prev_text' => '&laquo;',
                        'next_text' => '&raquo;',
                    ) );
                }
                ?>
            </div>
        </div>
        
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th width="5%">ID</th>
                    <th width="10%">平台</th>
                    <th width="40%">URL</th>
                    <th width="10%">状态</th>
                    <th width="15%">提交时间</th>
                    <th width="20%">响应</th>
                </tr>
            </thead>
            <tbody>
                <?php if ( $logs ) : ?>
                    <?php foreach ( $logs as $log ) : ?>
                        <tr>
                            <td><?php echo $log->id; ?></td>
                            <td><?php echo esc_html( $log->platform ); ?></td>
                            <td>
                                <a href="<?php echo esc_url( $log->url ); ?>" target="_blank" title="<?php echo esc_attr( $log->url ); ?>">
                                    <?php echo esc_html( substr( $log->url, 0, 50 ) . ( strlen( $log->url ) > 50 ? '...' : '' ) ); ?>
                                </a>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo esc_attr( $log->status ); ?>">
                                    <?php echo esc_html( $log->status ); ?>
                                </span>
                            </td>
                            <td><?php echo date( 'Y-m-d H:i:s', strtotime( $log->submitted_at ) ); ?></td>
                            <td>
                                <?php if ( $log->response ) : ?>
                                    <a href="#" class="view-response" data-response="<?php echo esc_attr( $log->response ); ?>">查看详情</a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                            <td colspan="6" style="text-align: center;">暂无提交记录</td>
                        </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('.view-response').on('click', function(e) {
            e.preventDefault();
            var response = $(this).data('response');
            var responseText = response;
            
            try {
                // 尝试解析JSON
                var parsed = JSON.parse(response);
                responseText = JSON.stringify(parsed, null, 2);
            } catch(e) {}
            
            alert('API响应:\n\n' + responseText);
        });
    });
    </script>
    
    <style>
    .status-badge { 
        padding: 3px 8px; 
        border-radius: 3px; 
        font-size: 12px; 
        font-weight: bold; 
    }
    .status-success { background: #d4edda; color: #155724; }
    .status-error { background: #f8d7da; color: #721c24; }
    .status-info { background: #d1ecf1; color: #0c5460; }
    .status-recorded { background: #fff3cd; color: #856404; }
    </style>
    <?php
}
?>

3. 独立的插件版本(复制到插件文件)

<?php
/**
 * Plugin Name: 404死链接自动提交
 * Plugin URI: https://yourdomain.com/
 * Description: 自动检测并提交404死链接到各大站长平台
 * Version: 1.0.0
 * Author: Your Name
 * License: GPL v2 or later
 */

// 防止直接访问
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// 定义插件常量
define( 'WPS_404_SUBMITTER_VERSION', '1.0.0' );
define( 'WPS_404_SUBMITTER_PATH', plugin_dir_path( __FILE__ ) );
define( 'WPS_404_SUBMITTER_URL', plugin_dir_url( __FILE__ ) );

// 包含核心文件
require_once WPS_404_SUBMITTER_PATH . 'includes/core.php';
require_once WPS_404_SUBMITTER_PATH . 'includes/admin.php';
require_once WPS_404_SUBMITTER_PATH . 'includes/api.php';

// 激活插件时创建表
register_activation_hook( __FILE__, 'wps_404_submitter_activate' );
function wps_404_submitter_activate() {
    require_once WPS_404_SUBMITTER_PATH . 'includes/activator.php';
    WPS_404_Submitter_Activator::activate();
}

// 停用插件时清理
register_deactivation_hook( __FILE__, 'wps_404_submitter_deactivate' );
function wps_404_submitter_deactivate() {
    require_once WPS_404_SUBMITTER_PATH . 'includes/deactivator.php';
    WPS_404_Submitter_Deactivator::deactivate();
}

4. 高级功能扩展

4.1 批量处理历史404链接

<?php
/**
 * 批量提交历史404链接
 */
function batch_submit_history_404() {
    global $wpdb;
    
    // 获取最近7天的404记录
    $table_name = $wpdb->prefix . '404_links_log';
    $seven_days_ago = date( 'Y-m-d H:i:s', strtotime( '-7 days' ) );
    
    $history_404 = $wpdb->get_col( 
        $wpdb->prepare( 
            "SELECT DISTINCT url FROM $table_name 
             WHERE platform = 'record' 
             AND submitted_at > %s 
             AND status = 'recorded'", 
            $seven_days_ago 
        ) 
    );
    
    $submitted_count = 0;
    foreach ( $history_404 as $url ) {
        if ( ! is_link_submitted( $url ) ) {
            submit_to_webmasters( $url );
            $submitted_count++;
            
            // 防止请求过快
            sleep( 1 );
        }
    }
    
    return $submitted_count;
}

// 添加定时任务
add_action( 'wp', 'schedule_404_batch_submit' );
function schedule_404_batch_submit() {
    if ( ! wp_next_scheduled( 'wps_daily_404_submit' ) ) {
        wp_schedule_event( time(), 'daily', 'wps_daily_404_submit' );
    }
}

add_action( 'wps_daily_404_submit', 'execute_daily_404_submit' );
function execute_daily_404_submit() {
    $count = batch_submit_history_404();
    
    // 发送邮件通知
    if ( $count > 0 ) {
        $admin_email = get_option( 'admin_email' );
        $subject = '[' . get_bloginfo( 'name' ) . '] 404链接批量提交报告';
        $message = "已批量提交 {$count} 个404链接到站长平台\n";
        $message .= "时间: " . current_time( 'mysql' ) . "\n";
        $message .= "网站: " . home_url();
        
        wp_mail( $admin_email, $subject, $message );
    }
}
?>

4.2 404页面建议功能

<?php
/**
 * 在404页面显示相关建议
 */
add_filter( '404_template', 'enhance_404_page' );
function enhance_404_page( $template ) {
    global $wp_query;
    
    $requested_url = get_current_url();
    
    // 记录404访问
    log_404_access( $requested_url );
    
    // 尝试查找相似页面
    $suggestions = find_similar_pages( $requested_url );
    
    if ( ! empty( $suggestions ) ) {
        add_action( 'wp_footer', function() use ( $suggestions ) {
            echo '<div id="404-suggestions" style="display:none;">';
            echo json_encode( array( 'suggestions' => $suggestions ) );
            echo '</div>';
            ?>
            <script>
            document.addEventListener('DOMContentLoaded', function() {
                var suggestions = JSON.parse(document.getElementById('404-suggestions').textContent);
                if (suggestions.suggestions.length > 0) {
                    var container = document.createElement('div');
                    container.className = '404-suggestions-container';
                    container.innerHTML = '<h3>您是不是在找:</h3><ul>' + 
                        suggestions.suggestions.map(function(s) {
                            return '<li><a href="' + s.url + '">' + s.title + '</a></li>';
                        }).join('') + '</ul>';
                    
                    var content = document.querySelector('.page-content') || document.querySelector('#content') || document.body;
                    if (content) {
                        content.appendChild(container);
                    }
                }
            });
            </script>
            <style>
            .404-suggestions-container {
                background: #f8f9fa;
                border-left: 4px solid #0073aa;
                padding: 20px;
                margin: 30px 0;
                border-radius: 4px;
            }
            .404-suggestions-container h3 {
                margin-top: 0;
                color: #333;
            }
            .404-suggestions-container ul {
                list-style: none;
                padding-left: 0;
            }
            .404-suggestions-container li {
                margin: 10px 0;
            }
            .404-suggestions-container a {
                color: #0073aa;
                text-decoration: none;
                font-size: 16px;
            }
            .404-suggestions-container a:hover {
                text-decoration: underline;
            }
            </style>
            <?php
        });
    }
    
    return $template;
}

/**
 * 查找相似页面
 */
function find_similar_pages( $url ) {
    $parsed_url = parse_url( $url );
    $path = $parsed_url['path'] ?? '';
    $slug = basename( $path );
    
    if ( empty( $slug ) ) {
        return array();
    }
    
    // 移除扩展名
    $slug = preg_replace( '/\\.[^.\\s]{3,4}$/', '', $slug );
    
    // 搜索相似的帖子/页面
    $args = array(
        'post_type'      => array( 'post', 'page' ),
        'post_status'    => 'publish',
        's'              => $slug,
        'posts_per_page' => 5,
    );
    
    $query = new WP_Query( $args );
    $suggestions = array();
    
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $suggestions[] = array(
                'title' => get_the_title(),
                'url'   => get_permalink(),
            );
        }
        wp_reset_postdata();
    }
    
    return $suggestions;
}
?>

5. 快速安装和使用指南

安装步骤:

  1. 方法一(主题集成)
    • 复制”核心功能文件”代码到主题的 functions.php
    • 复制”后台设置页面”代码到 functions.php
    • 访问WordPress后台 → 点击”404提交”菜单 → 配置API密钥
  2. 方法二(独立插件)
    • 创建文件夹 /wp-content/plugins/404-link-submitter/
    • 创建文件 404-link-submitter.php,粘贴”独立的插件版本”代码
    • 创建对应子文件夹和文件
    • 在插件页面激活插件

配置步骤:

  1. 登录各个站长平台获取API密钥
  2. 进入WordPress后台 → 404提交 → 设置
  3. 填写各平台API密钥并启用
  4. 访问一个不存在的页面测试(如:你的网站/不存在的页面

验证是否工作:

  1. 访问一个不存在的URL触发404
  2. 查看”提交日志”页面是否有记录
  3. 查看站长平台的”死链提交”记录

6. 安全注意事项

<?php
/**
 * 安全增强功能
 */

// 1. 限制提交频率
function check_submission_rate_limit( $ip ) {
    $transient_key = 'submission_limit_' . $ip;
    $submissions = get_transient( $transient_key ) ?: 0;
    
    if ( $submissions > 10 ) { // 每小时最多10次
        return false;
    }
    
    set_transient( $transient_key, $submissions + 1, HOUR_IN_SECONDS );
    return true;
}

// 2. 验证URL格式
function is_valid_url_to_submit( $url ) {
    $site_url = home_url();
    
    // 只提交本站链接
    if ( strpos( $url, $site_url ) !== 0 ) {
        return false;
    }
    
    // 排除某些路径
    $excluded_paths = array(
        '/wp-admin/',
        '/wp-includes/',
        '/wp-json/',
        '/xmlrpc.php',
        '/feed/',
    );
    
    foreach ( $excluded_paths as $path ) {
        if ( strpos( $url, $path ) !== false ) {
            return false;
        }
    }
    
    // 验证URL格式
    return filter_var( $url, FILTER_VALIDATE_URL ) !== false;
}

// 3. 添加nonce验证
add_action( 'admin_post_submit_manual_404', 'handle_manual_submission' );
function handle_manual_submission() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( '权限不足' );
    }
    
    check_admin_referer( 'manual_404_submission' );
    
    $urls = isset( $_POST['404_urls'] ) ? explode( "\n", $_POST['404_urls'] ) : array();
    $urls = array_map( 'trim', $urls );
    $urls = array_filter( $urls );
    
    $count = 0;
    foreach ( $urls as $url ) {
        if ( is_valid_url_to_submit( $url ) && ! is_link_submitted( $url ) ) {
            submit_to_webmasters( $url );
            $count++;
        }
    }
    
    wp_redirect( add_query_arg( 'submitted', $count, wp_get_referer() ) );
    exit;
}
?>

🎯 一键复制区(最简版本)

<?php
/* 最简版本 - 只需配置百度站长token即可使用 */
add_action( 'template_redirect', 'simple_404_submitter' );
function simple_404_submitter() {
    if ( is_404() ) {
        $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        
        // 配置你的百度站长token
        $baidu_token = '你的百度token';
        $site_url = home_url();
        
        if ( ! empty( $baidu_token ) ) {
            $api_url = 'http://data.zz.baidu.com/urls?site=' . urlencode( $site_url ) . '&token=' . $baidu_token;
            
            wp_remote_post( $api_url, array(
                'body'    => $current_url,
                'headers' => array( 'Content-Type' => 'text/plain' ),
            ) );
            
            // 记录日志
            global $wpdb;
            $wpdb->insert(
                $wpdb->prefix . '404_links',
                array(
                    'url' => $current_url,
                    'submitted_at' => current_time( 'mysql' ),
                )
            );
        }
    }
}
?>

📊 功能特性总结

功能支持情况
百度站长平台
Bing Webmaster
搜狗站长平台
Google Search Console⚠️ 需额外配置
防重复提交
提交日志记录
后台管理界面
批量处理
404页面建议
速率限制
安全验证

💡 提示:建议先在小流量网站测试,确认无误后再部署到生产环境。

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI里面继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为10万多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

如何让线上业务更上一层楼

还没有WordPress网站

还没有WordPress网站

不管你从事什么行业,WordPress都会为你提供一个专业的主题模板。在WordPress市场上有成千上万的免费主题,适合很多中小企业。

查看所有模板
已经有WordPress网站

已经有WordPress网站

小兽WordPress诚邀你一起学习WordPress,愿与各方携手升级改善您的WordPress网站,一起交流网站加速,网站优化等问题。

马上交个朋友
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部