You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wordpress使用递归函数调用Spoonacular API无法重复触发问题排查

问题排查与修复方案

核心问题点

  • 全局变量作用域错误:你在函数外定义的$apiKey没有在函数内声明为全局变量,导致API请求时密钥为空,接口返回错误,后续触发递归的POST请求不会执行。
  • API参数错误:Spoonacular的配料自动补全接口仅支持number参数控制返回结果数量,不存在per_page参数,你设置的per_page规则不会生效。
  • 缺少递归终止条件:现有代码没有设置递归停止的判断规则,即使递归正常触发也会无限循环,持续消耗API请求额度。
  • 非阻塞请求兼容性问题:部分WordPress运行环境不支持blocking=false的非阻塞请求,会导致后续的admin-ajax调用无法正常发出。
  • 写入权限校验:需确认你的当前主题目录有可写权限,否则report.txt无法生成和写入内容。

修复后代码

<?php
$apiKey = '替换为你自己的真实API密钥';

function get_ingredients_from_api() {
    // 引入全局变量API密钥
    global $apiKey;
    $file = get_stylesheet_directory() . '/report.txt';
    
    $current_ingredient = ( ! empty( $_POST[ 'current_ingredient' ] ) ) ? intval($_POST[ 'current_ingredient' ]) : 1 ;
    // 递归终止条件:超过50就停止
    if ($current_ingredient > 50) {
        return false;
    }

    $ingredients = [];
    // 调整API请求参数,number设为你需要的单页返回量,这里如果要每次拉1条递增就保持现有逻辑,要一次拉50就直接设number=50
    $response = wp_remote_get('https://api.spoonacular.com/food/ingredients/autocomplete?query=appl&number=1&apiKey=' . $apiKey, [
        'sslverify' => false
    ]);
    $results = wp_remote_retrieve_body($response);

    // 写入调试日志
    file_put_contents( $file, "Current Ingredient: " . $current_ingredient. PHP_EOL, FILE_APPEND);

    $results = json_decode($results);
    if ( ! is_array( $results ) || empty( $results ) ) {
        return false;
    }

    $next_ingredient = $current_ingredient + 1;
    // 测试阶段可以先把blocking设为true确认请求能正常发出,稳定后再改回false提升性能
    wp_remote_post( admin_url('admin-ajax.php?action=get_ingredients_from_api'), [
        'blocking' => true,
        'sslverify' => false,
        'body' => [
            'current_ingredient' => $next_ingredient
        ]
    ]);
}

add_action('wp_ajax_nopriv_get_ingredients_from_api', 'get_ingredients_from_api');
add_action('wp_ajax_get_ingredients_from_api', 'get_ingredients_from_api');
?>

使用说明

替换代码中的API密钥为你自己的真实密钥后,首次触发需要主动访问一次{你的站点域名}/wp-admin/admin-ajax.php?action=get_ingredients_from_api即可启动递归拉取流程。

内容的提问来源于stack exchange,提问作者LAF_OUT_LOUD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:30:04