loop – Portfolio items created indefinitely from external API. Every time different number


I am trying to make new portfolio item for every json item from external api. I am working on WordPress and placed my code in functions.php of the theme used. When i run my code, it creates portfolio items more than necessary. The items seem to randomly get duplicated even tho i have made validation statement and made sure that each post lug is unique. I want it to stop when the array in json file finishes. Unfortunately I can’t share the api link because it is not supposed to be open-source. It consists of one page. $model and $results get correct info. I am new to these WP functions and API thing and got really confused at this point. Hope someone can help me out!:

add_action('wp_ajax_nopriv_get_3dmodels_from_api', 'get_3dmodels_from_api');
add_action('wp_ajax_get_3dmodels_from_api', 'get_3dmodels_from_api');

function get_3dmodels_from_api(){
    $results = wp_remote_retrieve_body(wp_remote_get('<api-url-here>',  array(
        'timeout'     => 120,
        'httpversion' => '1.1',
    ) ) );  
    $results = json_decode($results);

    foreach($results->scenes as $model) {
        $model_slug = sanitize_title($model->name. '-' . $model->id);
        $existing_model = get_page_by_path($model_slug, 'OBJECT', 'portfolio');

        if ($existing_model === null) {

            $inserted_model = wp_insert_post([
                'post_name'=> $model_slug,
                'post_title'=> $model_slug,
                'post_type'=> 'portfolio',
                'post_status' => 'publish',
            if (is_wp_error($inserted_model)) {
                return false;
            $fillable = [
                'field_605dcef7001bc' => 'name',
                'field_605dcf01001bd' => 'description',
                'field_605dcf09001be' => 'category',
                'field_605dcf13001bf' => 'preview',
            foreach($fillable as $key => $name) {
                $model_content = $model->$name;
                if ($name == 'preview') {
                    $model_content="<img src="https://wordpress.stackexchange.com/questions/386061/. $model->$name ."" alt="">';
                update_field($key, $model_content, $inserted_model);
wp_remote_post(admin_url ('admin-ajax.php?action=get_3dmodels_from_api'), [
        'blocking' => false,
        'sslverify' => false,

Thank you!

coding_newbie 2 years 2021-04-02T06:16:19-05:00 0 Answers 0 views 0

Leave an answer