WordPress开发笔记

WordPress发布文章时将文章静态化为HTML文档

function zzw_regenerate_static_html_on_save($post_id) {
    // 防止自动保存时触发
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    
    // 获取文章URL
    $url = get_permalink($post_id);
    
    // 添加随机参数避免缓存
    $nocache_url = add_query_arg('nocache', time(), $url);
    
    // 设置请求参数
    $args = [
        'sslverify' => false, // 本地环境可跳过SSL验证
        'timeout'   => 120,   // 长超时防止超时
        'headers'   => [
            'Cache-Control' => 'no-cache',
            'X-Static-Gen'  => 'true' // 自定义头供插件识别
        ]
    ];
    
    // 发送内部请求
    $response = wp_remote_get($nocache_url, $args);
    
    if (!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
        $html = wp_remote_retrieve_body($response);
        
        // 保存路径 (示例:/wp-content/static/)
        $save_path = WP_CONTENT_DIR . '/static/' . $post_id . '.html';
        
        // 确保目录存在
        wp_mkdir_p(dirname($save_path));
        
        // 写入文件
        file_put_contents($save_path, $html);
    }
}
add_action('save_post', 'zzw_regenerate_static_html_on_save', 99, 1);