小红书AI自动写文章教程与WordPress高级定制开发方法

小红书AI写作工具API接入基础

小红书AI写作功能通过其开放API接口实现,首先需要获取有效的API密钥。登录小红书开发者平台,创建应用后即可获得专属API密钥和访问令牌。这些凭证是后续所有集成工作的基础。

在WordPress中接入小红书AI API,最直接的方式是创建自定义插件。以下是一个基础插件框架代码:


<?php
/
Plugin Name: 小红书AI写作集成
Description: 将小红书AI写作功能集成到WordPress中
Version: 1.0
Author: AI技术团队
/

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

// 定义API常量
define('XIAOHONGSHU_API_URL', 'https://api.xiaohongshu.com/v1/ai/write');
define('XIAOHONGSHU_API_KEY', 'your_api_key_here');
define('XIAOHONGSHU_API_SECRET', 'your_api_secret_here');

// 初始化插件
function xiaohongshu_ai_init() {
    // 添加后台菜单
    add_action('admin_menu', 'xiaohongshu_ai_admin_menu');
    // 注册AJAX处理函数
    add_action('wp_ajax_generate_content', 'xiaohongshu_ai_generate_content');
}
add_action('init', 'xiaohongshu_ai_init');
?>

这段代码创建了一个基础插件结构,定义了必要的常量和初始化函数。注意将`your_api_key_here`和`your_api_secret_here`替换为你从小红书开发者平台获取的实际凭证。

高级功能定制:多模型切换实现

为了增强灵活性,我们需要实现多种AI模型之间的无缝切换功能。小红书AI写作平台提供了多个模型选项,每个模型适用于不同类型的写作任务。

以下实现了一个模型选择器,并保存用户偏好:


// 添加模型选择器到文章编辑界面
function xiaohongshu_ai_add_model_selector() {
    global $post;
    
    // 获取当前选中的模型
    $selected_model = get_post_meta($post->ID, '_xiaohongshu_ai_model', true);
    if (!$selected_model) {
        $selected_model = 'general'; // 默认模型
    }
    
    // 可用模型列表
    $models = array(
        'general' => '通用写作模型',
        'creative' => '创意写作模型',
        'technical' => '技术文档模型',
        'marketing' => '营销文案模型'
    );
    
    echo '<div class="misc-pub-section">';
    echo '<label>AI写作模型: </label>';
    echo '<select id="xiaohongshu_ai_model" name="xiaohongshu_ai_model">';
    
    foreach ($models as $value => $label) {
        echo '<option value="' . esc_attr($value) . '" ' . selected($selected_model, $value, false) . '>';
        echo esc_html($label);
        echo '</option>';
    }
    
    echo '</select>';
    echo '</div>';
}
add_action('post_submitbox_misc_actions', 'xiaohongshu_ai_add_model_selector');

// 保存模型选择
function xiaohongshu_ai_save_model($post_id) {
    if (isset($_POST['xiaohongshu_ai_model'])) {
        update_post_meta($post_id, '_xiaohongshu_ai_model', sanitize_text_field($_POST['xiaohongshu_ai_model']));
    }
}
add_action('save_post', 'xiaohongshu_ai_save_model');

这段代码在WordPress文章编辑界面添加了一个模型选择器,并保存用户的选择。通过这种方式,用户可以根据不同文章类型选择最适合的AI写作模型。

定制化写作模板系统

为了提高AI生成内容的相关性和一致性,我们需要实现一个模板系统。这个系统允许用户创建和管理写作模板,AI将根据这些模板生成内容。

以下是模板系统的实现代码:


// 创建模板数据库表
function xiaohongshu_ai_create_templates_table() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'xiaohongshu_ai_templates';
    
    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        name varchar(100) NOT NULL,
        template text NOT NULL,
        model varchar(50) NOT NULL,
        created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'xiaohongshu_ai_create_templates_table');

// 添加模板管理菜单
function xiaohongshu_ai_templates_admin_menu() {
    add_submenu_page(
        'xiaohongshu_ai_settings',
        'AI写作模板管理',
        '模板管理',
        'manage_options',
        'xiaohongshu_ai_templates',
        'xiaohongshu_ai_templates_page'
    );
}
add_action('admin_menu', 'xiaohongshu_ai_templates_admin_menu');

// 渲染模板管理页面
function xiaohongshu_ai_templates_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'xiaohongshu_ai_templates';
    
    // 处理表单提交
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['template_name'])) {
        $name = sanitize_text_field($_POST['template_name']);
        $template = wp_kses_post($_POST['template_content']);
        $model = sanitize_text_field($_POST['template_model']);
        
        $wpdb->insert(
            $table_name,
            array(
                'name' => $name,
                'template' => $template,
                'model' => $model,
                'created_at' => current_time('mysql')
            )
        );
        
        echo '<div class="notice notice-success"><p>模板已成功保存!</p></div>';
    }
    
    // 获取所有模板
    $templates = $wpdb->get_results("SELECT  FROM $table_name ORDER BY created_at DESC");
    
    // 显示页面内容
    echo '<div class="wrap">';
    echo '<h1>AI写作模板管理</h1>';
    
    // 添加新模板表单
    echo '<h2>添加新模板</h2>';
    echo '<form method="post">';
    echo '<table class="form-table">';
    echo '<tr>';
    echo '<th scope="row"><label for="template_name">模板名称</label></th>';
    echo '<td><input type="text" id="template_name" name="template_name" class="regular-text" required></td>';
    echo '</tr>';
    echo '<tr>';
    echo '<th scope="row"><label for="template_model">适用模型</label></th>';
    echo '<td>';
    echo '<select id="template_model" name="template_model">';
    echo '<option value="general">通用写作模型</option>';
    echo '<option value="creative">创意写作模型</option>';
    echo '<option value="technical">技术文档模型</option>';
    echo '<option value="marketing">营销文案模型</option>';
    echo '</select>';
    echo '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<th scope="row"><label for="template_content">模板内容</label></th>';
    echo '<td><textarea id="template_content" name="template_content" rows="10" class="large-text" required></textarea>';
    echo '<p class="description">使用{关键词}作为变量占位符,AI将自动替换这些变量。</p></td>';
    echo '</tr>';
    echo '</table>';
    echo '<p><input type="submit" class="button button-primary" value="保存模板"></p>';
    echo '</form>';
    
    // 显示现有模板
    echo '<h2>现有模板</h2>';
    if ($templates) {
        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr><th>ID</th><th>名称</th><th>模型</th><th>创建时间</th><th>操作</th></tr></thead>';
        echo '<tbody>';
        foreach ($templates as $template) {
            echo '<tr>';
            echo '<td>' . esc_html($template->id) . '</td>';
            echo '<td>' . esc_html($template->name) . '</td>';
            echo '<td>' . esc_html($template->model) . '</td>';
            echo '<td>' . esc_html($template->created_at) . '</td>';
            echo '<td>';
            echo '<a href="" class="button" onclick="useTemplate(' . $template->id . '); return false;">使用</a> ';
            echo '<a href="" class="button" onclick="editTemplate(' . $template->id . '); return false;">编辑</a> ';
            echo '<a href="" class="button" onclick="deleteTemplate(' . $template->id . '); return false;">删除</a>';
            echo '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    } else {
        echo '<p>暂无模板,请添加新模板。</p>';
    }
    
    echo '</div>';
}

这段代码创建了一个完整的模板管理系统,包括数据库表创建、管理界面和模板操作功能。用户可以创建、编辑、删除和使用模板,AI将根据这些模板生成更加符合需求的内容。

高级内容生成与自动发布功能

为了实现完全自动化的内容生成和发布流程,我们需要开发一个高级功能,结合模板系统、模型选择和定时发布机制。

以下是实现这一功能的代码:


// 添加自动发布设置界面
function xiaohongshu_ai_auto_publish_settings() {
    add_settings_section(
        'xiaohongshu_ai_auto_publish_section',
        '自动发布设置',
        'xiaohongshu_ai_auto_publish_section_callback',
        'xiaohongshu_ai_settings'
    );
    
    add_settings_field(
        'xiaohongshu_ai_enable_auto_publish',
        '启用自动发布',
        'xiaohongshu_ai_enable_auto_publish_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_auto_publish_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_publish_frequency',
        '发布频率',
        'xiaohongshu_ai_publish_frequency_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_auto_publish_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_publish_time',
        '发布时间',
        'xiaohongshu_ai_publish_time_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_auto_publish_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_default_category',
        '默认分类',
        'xiaohongshu_ai_default_category_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_auto_publish_section'
    );
    
    register_setting('xiaohongshu_ai_settings', 'xiaohongshu_ai_auto_publish_options');
}
add_action('admin_init', 'xiaohongshu_ai_auto_publish_settings');

// 渲染自动发布设置回调函数
function xiaohongshu_ai_auto_publish_section_callback() {
    echo '<p>配置AI自动生成内容并发布的参数。</p>';
}

function xiaohongshu_ai_enable_auto_publish_callback() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    $enabled = isset($options['enable_auto_publish']) ? $options['enable_auto_publish'] : 0;
    echo '<input type="checkbox" id="xiaohongshu_ai_enable_auto_publish" name="xiaohongshu_ai_auto_publish_options[enable_auto_publish]" value="1" ' . checked(1, $enabled, false) . ' />';
    echo '<label for="xiaohongshu_ai_enable_auto_publish">启用自动发布功能</label>';
}

function xiaohongshu_ai_publish_frequency_callback() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    $frequency = isset($options['publish_frequency']) ? $options['publish_frequency'] : 'daily';
    echo '<select id="xiaohongshu_ai_publish_frequency" name="xiaohongshu_ai_auto_publish_options[publish_frequency]">';
    echo '<option value="daily" ' . selected('daily', $frequency, false) . '>每天</option>';
    echo '<option value="twicedaily" ' . selected('twicedaily', $frequency, false) . '>每天两次</option>';
    echo '<option value="weekly" ' . selected('weekly', $frequency, false) . '>每周</option>';
    echo '</select>';
}

function xiaohongshu_ai_publish_time_callback() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    $time = isset($options['publish_time']) ? $options['publish_time'] : '09:00';
    echo '<input type="time" id="xiaohongshu_ai_publish_time" name="xiaohongshu_ai_auto_publish_options[publish_time]" value="' . esc_attr($time) . '" />';
}

function xiaohongshu_ai_default_category_callback() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    $category = isset($options['default_category']) ? $options['default_category'] : 1;
    wp_dropdown_categories(array(
        'show_option_none' => '选择分类',
        'option_none_value' => '0',
        'name' => 'xiaohongshu_ai_auto_publish_options[default_category]',
        'selected' => $category,
        'hide_empty' => 0
    ));
}

// 注册定时任务
function xiaohongshu_ai_activate_cron() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    if (isset($options['enable_auto_publish']) && $options['enable_auto_publish']) {
        $frequency = isset($options['publish_frequency']) ? $options['publish_frequency'] : 'daily';
        if (!wp_next_scheduled('xiaohongshu_ai_auto_publish_event')) {
            wp_schedule_event(time(), $frequency, 'xiaohongshu_ai_auto_publish_event');
        }
    }
}
add_action('wp', 'xiaohongshu_ai_activate_cron');

// 添加定时任务钩子
add_action('xiaohongshu_ai_auto_publish_event', 'xiaohongshu_ai_execute_auto_publish');

// 执行自动发布
function xiaohongshu_ai_execute_auto_publish() {
    $options = get_option('xiaohongshu_ai_auto_publish_options');
    
    // 检查是否启用自动发布
    if (!isset($options['enable_auto_publish']) || !$options['enable_auto_publish']) {
        return;
    }
    
    // 获取默认分类
    $category_id = isset($options['default_category']) ? intval($options['default_category']) : 1;
    
    // 获取随机模板
    global $wpdb;
    $table_name = $wpdb->prefix . 'xiaohongshu_ai_templates';
    $template = $wpdb->get_row("SELECT  FROM $table_name ORDER BY RAND() LIMIT 1");
    
    if (!$template) {
        return; // 没有可用模板
    }
    
    // 准备API请求数据
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => $template->model,
        'template' => $template->template,
        'variables' => array(
            '关键词' => xiaohongshu_ai_get_random_keywords(),
            '日期' => current_time('Y-m-d'),
            '网站名称' => get_bloginfo('name')
        )
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    // 检查响应
    if (is_wp_error($response)) {
        error_log('小红书AI API请求失败: ' . $response->get_error_message());
        return;
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['content'])) {
        error_log('小红书AI API响应解析失败');
        return;
    }
    
    // 创建文章
    $post_data = array(
        'post_title'    => wp_strip_all_tags($data['title']),
        'post_content'  => $data['content'],
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_category' => array($category_id),
        'tags_input'    => explode(',', $data['tags'])
    );
    
    $post_id = wp_insert_post($post_data);
    
    if (is_wp_error($post_id)) {
        error_log('自动发布文章失败: ' . $post_id->get_error_message());
        return;
    }
    
    // 记录日志
    error_log('成功自动发布文章: ' . $post_id);
}

// 获取随机关键词
function xiaohongshu_ai_get_random_keywords() {
    // 这里可以根据你的需求实现关键词获取逻辑
    // 例如从预设列表中随机选择,或从其他API获取热门关键词
    $keywords = array('人工智能', '机器学习', '深度学习', '自然语言处理', '计算机视觉');
    return $keywords[array_rand($keywords)];
}

这段代码实现了一个完整的自动发布系统,包括设置界面、定时任务调度和内容生成发布逻辑。用户可以配置自动发布的频率、时间和默认分类,系统将根据这些设置自动生成内容并发布到WordPress网站。

高级SEO优化与内容质量控制

为了确保AI生成的内容具有良好的SEO表现和质量,我们需要实现一系列高级优化功能。以下代码实现了关键词密度控制、内容质量评分和自动SEO优化:


// 添加SEO优化设置
function xiaohongshu_ai_seo_settings() {
    add_settings_section(
        'xiaohongshu_ai_seo_section',
        'SEO优化设置',
        'xiaohongshu_ai_seo_section_callback',
        'xiaohongshu_ai_settings'
    );
    
    add_settings_field(
        'xiaohongshu_ai_enable_seo_optimization',
        '启用SEO优化',
        'xiaohongshu_ai_enable_seo_optimization_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_seo_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_target_keywords',
        '目标关键词',
        'xiaohongshu_ai_target_keywords_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_seo_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_keyword_density',
        '关键词密度',
        'xiaohongshu_ai_keyword_density_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_seo_section'
    );
    
    add_settings_field(
        'xiaohongshu_ai_min_word_count',
        '最小字数',
        'xiaohongshu_ai_min_word_count_callback',
        'xiaohongshu_ai_settings',
        'xiaohongshu_ai_seo_section'
    );
    
    register_setting('xiaohongshu_ai_settings', 'xiaohongshu_ai_seo_options');
}
add_action('admin_init', 'xiaohongshu_ai_seo_settings');

// 渲染SEO设置回调函数
function xiaohongshu_ai_seo_section_callback() {
    echo '<p>配置AI生成内容的SEO优化参数。</p>';
}

function xiaohongshu_ai_enable_seo_optimization_callback() {
    $options = get_option('xiaohongshu_ai_seo_options');
    $enabled = isset($options['enable_seo_optimization']) ? $options['enable_seo_optimization'] : 0;
    echo '<input type="checkbox" id="xiaohongshu_ai_enable_seo_optimization" name="xiaohongshu_ai_seo_options[enable_seo_optimization]" value="1" ' . checked(1, $enabled, false) . ' />';
    echo '<label for="xiaohongshu_ai_enable_seo_optimization">启用SEO优化功能</label>';
}

function xiaohongshu_ai_target_keywords_callback() {
    $options = get_option('xiaohongshu_ai_seo_options');
    $keywords = isset($options['target_keywords']) ? $options['target_keywords'] : '';
    echo '<textarea id="xiaohongshu_ai_target_keywords" name="xiaohongshu_ai_seo_options[target_keywords]" rows="3" class="large-text">' . esc_textarea($keywords) . '</textarea>';
    echo '<p class="description">每行一个关键词,AI将优先使用这些关键词。</p>';
}

function xiaohongshu_ai_keyword_density_callback() {
    $options = get_option('xiaohongshu_ai_seo_options');
    $density = isset($options['keyword_density']) ? $options['keyword_density'] : '2.5';
    echo '<input type="number" id="xiaohongshu_ai_keyword_density" name="xiaohongshu_ai_seo_options[keyword_density]" value="' . esc_attr($density) . '" min="0.5" max="5" step="0.1" />';
    echo '<label for="xiaohongshu_ai_keyword_density">%</label>';
    echo '<p class="description">关键词密度建议设置在1%-3%之间。</p>';
}

function xiaohongshu_ai_min_word_count_callback() {
    $options = get_option('xiaohongshu_ai_seo_options');
    $count = isset($options['min_word_count']) ? $options['min_word_count'] : '800';
    echo '<input type="number" id="xiaohongshu_ai_min_word_count" name="xiaohongshu_ai_seo_options[min_word_count]" value="' . esc_attr($count) . '" min="300" max="5000" step="100" />';
    echo '<p class="description">文章最小字数,建议不少于800字。</p>';
}

// SEO优化处理函数
function xiaohongshu_ai_optimize_content($content, $title) {
    $options = get_option('xiaohongshu_ai_seo_options');
    
    // 检查是否启用SEO优化
    if (!isset($options['enable_seo_optimization']) || !$options['enable_seo_optimization']) {
        return $content;
    }
    
    // 获取目标关键词
    $target_keywords = isset($options['target_keywords']) ? explode("n", $options['target_keywords']) : array();
    $target_keywords = array_map('trim', $target_keywords);
    $target_keywords = array_filter($target_keywords);
    
    if (empty($target_keywords)) {
        return $content;
    }
    
    // 获取关键词密度
    $keyword_density = isset($options['keyword_density']) ? floatval($options['keyword_density']) : 2.5;
    $keyword_density = max(0.5, min(5, $keyword_density)) / 100; // 限制在0.5%-5%之间
    
    // 获取最小字数
    $min_word_count = isset($options['min_word_count']) ? intval($options['min_word_count']) : 800;
    
    // 计算当前字数
    $word_count = str_word_count(strip_tags($content));
    
    // 如果字数不足,扩展内容
    if ($word_count < $min_word_count) {
        $content = xiaohongshu_ai_expand_content($content, $min_word_count - $word_count, $target_keywords);
        $word_count = str_word_count(strip_tags($content));
    }
    
    // 计算当前关键词密度
    $content_lower = strtolower(strip_tags($content));
    $total_words = str_word_count($content_lower);
    
    foreach ($target_keywords as $keyword) {
        $keyword_count = substr_count($content_lower, strtolower($keyword));
        $current_density = ($keyword_count / $total_words)  100;
        
        // 如果关键词密度不足,增加关键词出现次数
        if ($current_density  0) {
                $content = xiaohongshu_ai_add_keywords($content, $keyword, $add_count);
            }
        }
    }
    
    // 添加SEO友好的标题标签
    $content = xiaohongshu_ai_add_heading_tags($content, $title);
    
    // 添加内部链接
    $content = xiaohongshu_ai_add_internal_links($content);
    
    return $content;
}

// 扩展内容函数
function xiaohongshu_ai_expand_content($content, $required_words, $keywords) {
    // 准备API请求
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => 'creative',
        'action' => 'expand',
        'content' => $content,
        'required_words' => $required_words,
        'keywords' => $keywords
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return $content; // 扩展失败,返回原内容
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['expanded_content'])) {
        return $content; // 解析失败,返回原内容
    }
    
    return $data['expanded_content'];
}

// 添加关键词函数
function xiaohongshu_ai_add_keywords($content, $keyword, $count) {
    $sentences = preg_split('/(?<=[.!?])s+/', $content);
    $total_sentences = count($sentences);
    $interval = max(1, floor($total_sentences / $count));
    
    for ($i = 0; $i  0; $i += $interval) {
        if (strpos($sentences[$i], $keyword) === false) {
            // 在句子中自然地插入关键词
            $words = explode(' ', $sentences[$i]);
            $position = rand(1, max(1, count($words) - 2));
            array_splice($words, $position, 0, $keyword);
            $sentences[$i] = implode(' ', $words);
            $count--;
        }
    }
    
    return implode(' ', $sentences);
}

// 添加标题标签函数
function xiaohongshu_ai_add_heading_tags($content, $title) {
    // 将第一个段落作为H2标题
    $content = preg_replace('/<p>([^<]+)</p>/', '<h2>$1</h2>', $content, 1);
    
    // 将其他段落中的标题转换为H3
    $content = preg_replace('/<p>([A-Z][^<]{10,100}?)</p>/', '<h3>$1</h3>', $content);
    
    return $content;
}

// 添加内部链接函数
function xiaohongshu_ai_add_internal_links($content) {
    // 获取相关文章
    $related_posts = get_posts(array(
        'numberposts' => 5,
        'orderby' => 'rand',
        'post_status' => 'publish'
    ));
    
    if (empty($related_posts)) {
        return $content;
    }
    
    // 在内容中随机位置添加内部链接
    $sentences = preg_split('/(?<=[.!?])s+/', $content);
    $total_sentences = count($sentences);
    $link_count = min(3, count($related_posts));
    $interval = max(1, floor($total_sentences / ($link_count + 1)));
    
    for ($i = $interval, $j = 0; $i < $total_sentences && $j post_title;
        $link_url = get_permalink($post->ID);
        
        // 在句子中添加链接
        $sentences[$i] .= ' 了解更多关于<a href="' . esc_url($link_url) . '">' . esc_html($link_text) . '</a>的信息。';
    }
    
    return implode(' ', $sentences);
}

这段代码实现了一个全面的SEO优化系统,包括关键词密度控制、内容扩展、标题标签优化和内部链接添加。通过这些功能,AI生成的内容将具有更好的SEO表现,更容易被搜索引擎收录和排名。

内容质量评估与自动优化

为了确保AI生成的内容质量,我们需要实现一个内容质量评估系统,并根据评估结果自动优化内容。以下代码实现了这一功能:


// 内容质量评估函数
function xiaohongshu_ai_evaluate_content_quality($content, $title) {
    $scores = array();
    
    // 评估可读性
    $scores['readability'] = xiaohongshu_ai_evaluate_readability($content);
    
    // 评估原创性
    $scores['originality'] = xiaohongshu_ai_evaluate_originality($content);
    
    // 评估结构化
    $scores['structure'] = xiaohongshu_ai_evaluate_structure($content);
    
    // 评估信息价值
    $scores['value'] = xiaohongshu_ai_evaluate_value($content);
    
    // 计算总分
    $total_score = (
        $scores['readability']  0.25 +
        $scores['originality']  0.3 +
        $scores['structure']  0.2 +
        $scores['value']  0.25
    );
    
    return array(
        'total' => round($total_score, 2),
        'breakdown' => $scores
    );
}

// 可读性评估函数
function xiaohongshu_ai_evaluate_readability($content) {
    $text = strip_tags($content);
    $sentences = preg_split('/[.!?]+/', $text);
    $sentences = array_filter($sentences);
    $words = preg_split('/s+/', $text);
    $words = array_filter($words);
    
    if (empty($sentences) || empty($words)) {
        return 0;
    }
    
    // 计算平均句子长度
    $avg_sentence_length = count($words) / count($sentences);
    
    // 计算平均词长
    $total_chars = array_sum(array_map('strlen', $words));
    $avg_word_length = $total_chars / count($words);
    
    // 计算可读性分数 (简化版Flesch Reading Ease)
    $readability_score = 206.835 - (1.015  $avg_sentence_length) - (84.6  ($avg_word_length / 4.71));
    
    // 将分数标准化到0-100范围
    $normalized_score = max(0, min(100, $readability_score));
    
    return $normalized_score / 100; // 返回0-1之间的值
}

// 原创性评估函数
function xiaohongshu_ai_evaluate_originality($content) {
    // 准备API请求
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => 'originality',
        'action' => 'check',
        'content' => $content
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return 0.5; // 请求失败,返回中等分数
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['originality_score'])) {
        return 0.5; // 解析失败,返回中等分数
    }
    
    return max(0, min(1, $data['originality_score'] / 100)); // 返回0-1之间的值
}

// 结构化评估函数
function xiaohongshu_ai_evaluate_structure($content) {
    $score = 0;
    
    // 检查标题结构
    if (preg_match('/<h[1-6]>.?</h[1-6]>/', $content)) {
        $score += 0.3;
    }
    
    // 检查段落结构
    $paragraphs = preg_split('/<p>.?</p>/', $content);
    if (count($paragraphs) > 3) {
        $score += 0.2;
    }
    
    // 检查列表结构
    if (preg_match('/<(ul|ol)>.?</(ul|ol)>/s', $content)) {
        $score += 0.2;
    }
    
    // 检查链接结构
    if (preg_match('/<a href=.?>.?</a>/', $content)) {
        $score += 0.15;
    }
    
    // 检查图片结构
    if (preg_match('/<img.?>/', $content)) {
        $score += 0.15;
    }
    
    return $score;
}

// 信息价值评估函数
function xiaohongshu_ai_evaluate_value($content) {
    // 准备API请求
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => 'value_assessment',
        'action' => 'evaluate',
        'content' => $content
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return 0.5; // 请求失败,返回中等分数
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['value_score'])) {
        return 0.5; // 解析失败,返回中等分数
    }
    
    return max(0, min(1, $data['value_score'] / 100)); // 返回0-1之间的值
}

// 自动优化内容函数
function xiaohongshu_ai_auto_optimize_content($content, $title) {
    // 评估内容质量
    $quality_scores = xiaohongshu_ai_evaluate_content_quality($content, $title);
    $total_score = $quality_scores['total'];
    $breakdown = $quality_scores['breakdown'];
    
    // 如果总分已经很高,直接返回
    if ($total_score >= 0.85) {
        return $content;
    }
    
    // 根据各项分数进行优化
    $optimized_content = $content;
    
    // 优化可读性
    if ($breakdown['readability'] < 0.7) {
        $optimized_content = xiaohongshu_ai_improve_readability($optimized_content);
    }
    
    // 优化原创性
    if ($breakdown['originality'] < 0.7) {
        $optimized_content = xiaohongshu_ai_improve_originality($optimized_content);
    }
    
    // 优化结构
    if ($breakdown['structure'] < 0.7) {
        $optimized_content = xiaohongshu_ai_improve_structure($optimized_content, $title);
    }
    
    // 优化信息价值
    if ($breakdown['value']  XIAOHONGSHU_API_KEY,
        'model' => 'readability',
        'action' => 'improve',
        'content' => $content
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return $content; // 请求失败,返回原内容
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['improved_content'])) {
        return $content; // 解析失败,返回原内容
    }
    
    return $data['improved_content'];
}

// 提高原创性函数
function xiaohongshu_ai_improve_originality($content) {
    // 准备API请求
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => 'originality',
        'action' => 'improve',
        'content' => $content
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return $content; // 请求失败,返回原内容
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['improved_content'])) {
        return $content; // 解析失败,返回原内容
    }
    
    return $data['improved_content'];
}

// 改善结构函数
function xiaohongshu_ai_improve_structure($content, $title) {
    // 确保有H2标题
    if (!preg_match('/<h2>.?</h2>/', $content)) {
        $paragraphs = preg_split('/<p>.?</p>/', $content, 2);
        if (isset($paragraphs[1])) {
            $first_paragraph = preg_replace('/</?p>/', '', $paragraphs[0]);
            $content = '<h2>' . $first_paragraph . '</h2>' . $paragraphs[1];
        }
    }
    
    // 确保有列表
    if (!preg_match('/<(ul|ol)>.?</(ul|ol)>/s', $content)) {
        // 尝试将一些内容转换为列表
        $content = preg_replace('/<p>([^<]?:[^<]?)</p><p>([^<]?:[^<]?)</p><p>([^<]?:[^<]?)</p>/s', '<ul><li>$1</li><li>$2</li><li>$3</li></ul>', $content);
    }
    
    return $content;
}

// 提高信息价值函数
function xiaohongshu_ai_improve_value($content) {
    // 准备API请求
    $api_data = array(
        'api_key' => XIAOHONGSHU_API_KEY,
        'model' => 'value',
        'action' => 'enhance',
        'content' => $content
    );
    
    // 发送API请求
    $response = wp_remote_post(XIAOHONGSHU_API_URL, array(
        'body' => json_encode($api_data),
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . XIAOHONGSHU_API_SECRET
        ),
        'timeout' => 30
    ));
    
    if (is_wp_error($response)) {
        return $content; // 请求失败,返回原内容
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['enhanced_content'])) {
        return $content; // 解析失败,返回原内容
    }
    
    return $data['enhanced_content'];
}

这段代码实现了一个全面的内容质量评估和自动优化系统。它从可读性、原创性、结构化和信息价值四个维度评估内容质量,并根据评估结果自动优化内容,确保AI生成的内容具有高质量和良好的用户体验。