【发布时间】:2021-10-20 18:33:44
【问题描述】:
我正在建立一个使用 Spoonacular API 的新 Wordpress 网站。 我想使用递归函数从 API 呈现 50 个项目,但我无法弄清楚为什么我的代码没有再次调用该函数。 我期望得到的结果是,创建的“report.txt”文件将显示一个不断更新的数字,直到指定的每页数“50”。 “report.txt”文件只显示默认数字“1”而不是递增。 我不确定是否再次调用该函数。 任何帮助是极大的赞赏。谢谢。
functions.php
<?php
$apiKey = '123456789';
function get_ingredients_from_api() {
$file = get_stylesheet_directory() . '/report.txt';
$current_ingredient = ( ! empty( $_POST[ 'current_ingredient' ] ) ) ? $_POST[ 'current_ingredient' ] : 1 ;
$ingredients = [];
$results = wp_remote_retrieve_body(
wp_remote_get('https://api.spoonacular.com/food/ingredients/autocomplete?query=appl&number=' . $current_ingredient . '&per_page=50&apiKey=' . $apiKey)
);
file_put_contents( $file, "Current Ingredient: " . $current_ingredient. "\n\n", FILE_APPEND);
$results = json_decode($results);
if ( ! is_array( $results ) || empty( $results ) ) {
return false;
}
$current_ingredient = $current_ingredient + 1;
wp_remote_post( admin_url('admin-ajax.php?action=get_ingredients_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_ingredient' => $current_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');
?>
【问题讨论】:
标签: php wordpress api recursion increment