AI生成文章的图像生成API调用教程 WordPress免费工具集成

获取AI图像生成API密钥

你需要先注册一个AI图像生成服务账户,例如OpenAI DALL-E或豆包AI。访问OpenAI官网,创建账户后导航到API密钥管理页面。生成新密钥时,确保选择适当的权限范围,仅限于图像生成功能。密钥生成后,立即复制并安全存储,避免泄露。如果使用豆包AI,登录豆包控制台,在API设置中生成密钥,注意豆包的免费额度限制,避免超出配额导致调用失败。

AI生成文章的图像生成API调用教程 WordPress免费工具集成

配置WordPress环境

在WordPress后台,确保你的站点运行在PHP 7.4或更高版本,以支持API调用。检查服务器是否启用cURL扩展,这是处理HTTP请求的必要组件。通过WordPress仪表盘,导航到“插件” > “安装插件”,搜索并安装“WP REST API”插件,激活它以启用RESTful接口。如果使用免费AI模型如通义千问,确认WordPress的内存限制设置为至少256MB,防止处理大图像时崩溃。

编写API调用代码

使用JavaScript在WordPress主题中集成API调用。在主题的functions.php文件中添加以下代码,确保替换YOUR_API_KEY为实际密钥。此代码调用OpenAI DALL-E API生成图像,并返回URL。


function generateImageWithAI(prompt) {
    const apiKey = 'YOUR_API_KEY';
    const apiUrl = 'https://api.openai.com/v1/images/generations';
    
    const data = {
        model: 'dall-e-3',
        prompt: prompt,
        n: 1,
        size: '1024x1024'
    };
    
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.data && data.data.length > 0) {
            const imageUrl = data.data[0].url;
            console.log('Generated Image URL:', imageUrl);
            return imageUrl;
        } else {
            console.error('Image generation failed:', data.error);
            return null;
        }
    })
    .catch(error => {
        console.error('API call error:', error);
        return null;
    });
}

对于豆包AI,修改API端点为豆包官方提供的URL,并调整参数结构。豆包的API要求prompt字段包含详细描述,例如“生成一张科技主题的博客配图”。在测试时,使用简单的prompt如“蓝色背景的抽象图案”验证功能。

集成到文章编辑器

在WordPress文章编辑器中添加自定义按钮,触发图像生成。在主题的JavaScript文件中添加以下代码,创建按钮并绑定事件。


document.addEventListener('DOMContentLoaded', function() {
    const editor = document.querySelector('.editor-post-title__input');
    if (editor) {
        const generateButton = document.createElement('button');
        generateButton.textContent = '生成AI图像';
        generateButton.style.marginLeft = '10px';
        generateButton.onclick = function() {
            const title = editor.value;
            if (title) {
                const prompt = `生成与文章标题相关的图像: ${title}`;
                generateImageWithAI(prompt).then(url => {
                    if (url) {
                        alert('图像生成成功,URL: ' + url);
                    } else {
                        alert('生成失败,请检查API设置');
                    }
                });
            } else {
                alert('请先输入文章标题');
            }
        };
        editor.parentNode.appendChild(generateButton);
    }
});

此代码在文章标题输入框旁添加按钮,点击后使用标题作为prompt调用API。如果使用智普AI,智普的API要求额外参数如style,需在data对象中添加style字段。智普的免费模型可能限制生成速度,建议在非高峰时段测试。

处理图像上传和存储

生成的图像URL需要下载并上传到WordPress媒体库。使用以下PHP代码在functions.php中实现自动上传。


function uploadImageToWordPress($imageUrl, $postId) {
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    
    $tmp = download_url($imageUrl);
    if (is_wp_error($tmp)) {
        return false;
    }
    
    $fileArray = array(
        'name' => basename($imageUrl),
        'tmp_name' => $tmp
    );
    
    $attachmentId = media_handle_sideload($fileArray, $postId);
    if (is_wp_error($attachmentId)) {
        @unlink($tmp);
        return false;
    }
    
    return $attachmentId;
}

调用此函数时,传入生成的图像URL和文章ID。对于通义千问,通义的API返回的URL有时效性,需立即下载。通义千问的免费额度允许每月100次调用,监控使用量避免超额。

配置错误处理和日志

在API调用中添加错误处理机制,确保失败时提供反馈。修改JavaScript代码以记录错误到WordPress数据库。


function logErrorToWordPress(error) {
    const logData = {
        action: 'log_api_error',
        error: error.message,
        timestamp: new Date().toISOString()
    };
    
    fetch('/wp-admin/admin-ajax.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams(logData)
    });
}

// 在generateImageWithAI的catch块中调用
.catch(error => {
    console.error('API call error:', error);
    logErrorToWordPress(error);
    return null;
});

在WordPress中添加AJAX处理函数接收日志。在functions.php中添加:


add_action('wp_ajax_log_api_error', 'handle_api_error_log');
function handle_api_error_log() {
    $error = sanitize_text_field($_POST['error']);
    $timestamp = sanitize_text_field($_POST['timestamp']);
    global $wpdb;
    $table_name = $wpdb->prefix . 'api_error_logs';
    $wpdb->insert(
        $table_name,
        array(
            'error_message' => $error,
            'timestamp' => $timestamp
        )
    );
    wp_die();
}

创建数据库表存储日志。对于Gemini AI,Gemini的API可能返回特定错误代码如rate_limit_exceeded,需在代码中检查并提示用户稍后重试。

优化API调用性能

使用缓存减少重复调用。在WordPress中安装并激活“WP Super Cache”插件,配置缓存规则。在JavaScript代码中添加缓存检查。


const imageCache = {};

function generateImageWithAI(prompt) {
    if (imageCache[prompt]) {
        return Promise.resolve(imageCache[prompt]);
    }
    
    // 原有API调用代码
    // 在成功时缓存结果
    .then(data => {
        if (data.data && data.data.length > 0) {
            const imageUrl = data.data[0].url;
            imageCache[prompt] = imageUrl;
            return imageUrl;
        }
    });
}

对于文言一心,文言一心的API响应时间较长,建议设置超时参数。在fetch请求中添加timeout选项。


fetch(apiUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify(data),
    signal: AbortSignal.timeout(30000) // 30秒超时
})

测试和验证集成

在WordPress测试环境中验证功能。创建新文章,输入标题如“AI技术发展趋势”,点击生成按钮。检查浏览器控制台输出和媒体库中是否上传图像。如果使用免费AI模型如豆包,豆包的API在免费层可能限制图像分辨率,生成的图像为512x512像素,需在代码中调整size参数为'512x512'。对于OpenAI DALL-E,DALL-E-3模型支持1024x1024分辨率,确保在data对象中指定。

测试错误场景:输入无效API密钥,验证错误日志记录。模拟网络超时,检查超时处理。如果使用智普AI,智普的API在免费模式下可能返回水印图像,需在生成后手动移除或升级计划。