【问题标题】:Wordpress - Using a recursive fn to render the data from an APIWordpress - 使用递归 fn 从 API 呈现数据
【发布时间】: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


    【解决方案1】:

    我意识到从代码中注释掉或删除 if 语句可以让函数完美运行。我不确定如何保留 if 语句并让函数运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 2021-06-30
      • 2020-09-28
      • 2020-03-10
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多