WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Import multiple post via API. (1 post)

  1. w1nk5
    Member
    Posted 2 years ago #

    Here is the function I am using to import posts from an API:

    /**
     * Import vehicles
     */
    function n4s_import_vehicles() {
    
    	ini_set('max_execution_time', 300);
    
    	//Initialize curl
    	$ch = curl_init(); 
    
    	curl_setopt($ch, CURLOPT_URL, 'http://api.curtmfg.com/v2/GetVehicle?year=&make=&model=&style=&dataType=JSON');
    	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    	$ch_data = curl_exec($ch);
    	curl_close($ch);  
    
    	if(!empty($ch_data)) {
    
    		$i = 0;
    
    		$json_data = json_decode($ch_data, true); //print_r(count($json_data)); exit();
    		foreach($json_data as $data) {
    
    			$post_title = $data['year'] . ' ' . $data['make'] . ' ' . $data['model'] . ' ' . $data['style'];
    
    			$post = array(
    				'post_type' => 'vehicle',
    				'post_status' => 'publish',
    				'post_title' => $post_title
    			);
    
    			$post_id = wp_insert_post($post);
    
    			$vehicle_year = str_replace('.', '-', $data['year']);
    			$vehicle_make = str_replace(' ', '-', strtolower($data['make']));
    
    			if(!empty($post_id)) {
    
    				// Update Year
    				wp_set_object_terms($post_id, $vehicle_year, 'vehicle_year');
    
    				// Update Make
    				wp_set_object_terms($post_id, $vehicle_make, 'make');
    
    				// Update Model
    				update_post_meta($post_id, 'n4s-vehicle-model', $data['model']);
    
    				// Update Style
    				update_post_meta($post_id, 'n4s-vehicle-style', $data['style']);
    			}
    
    			$i++;
    
    			if($i == 1000) {
    				$wpdb->queries = array();
    				$wp_actions = array();
    				wp_cache_flush();
    			}
    		}
    	}
    }

    This imports approx. 2500 - 6000 posts before breaking. Just over a minute. However, there are over 9000 posts that need to be inserted.

    Any insight on this issue would be greatly appreciated.

    Cheers

    [ Don't bump, that's not permitted here. ]

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.