Support » Allgemeine Fragen » Import WordPress über 10.000 Posts *arg

  • Hallo Liebe Community,
    für meine Arbeit habe ich ein Plugin erstellt, das auf die Daten von Mobile.de und einer API ( Json ) einer Autobörse zugreift. Das Problem was mich in den Wahnsinn treibt – Import geschwindigkeit – habe schon alles ausprobiert was ich im Netz gefunden habe. Momentan schafft es der script ohne cron ja noch nicht mal den fertigen Import von der API(Json). Mobile mit maximal 300 Importen functioniert langsam aber functioniert.

    Auszug Debug.log

    [16-Nov-2018 23:36:21 UTC] mobile.pid was created
    [16-Nov-2018 23:36:24 UTC] New Vehicle Read
    [16-Nov-2018 23:36:24 UTC] Old Vehicle Read
    [16-Nov-2018 23:36:24 UTC] 197 Vehicles in Stock
    [16-Nov-2018 23:36:24 UTC] 197 Vehicle Ids in Stock Unique
    [16-Nov-2018 23:36:24 UTC] 0 new Vehicles
    [16-Nov-2018 23:36:24 UTC] Clean UP
    [16-Nov-2018 23:36:24 UTC] mobile.pid was deleted

    das functioniert und juchu ;(

    Nun die Json abfrage –

    [16-Nov-2018 23:36:16 UTC] New Vehicle Read
    [16-Nov-2018 23:36:16 UTC] Old Vehicle Read
    [16-Nov-2018 23:36:16 UTC] 2942 Vehicles in Stock
    [16-Nov-2018 23:36:17 UTC] 18442 new Vehicles
    [16-Nov-2018 23:36:17 UTC] Import is running
    
    

    [16-Nov-2018 23:35:17 UTC] Vehicles insert
    [16-Nov-2018 23:35:17 UTC] After insert: 477.19774627686 MB
    // knapp 10 sec für einen Import ;-(
    [16-Nov-2018 23:35:26 UTC] Vehicles insert
    [16-Nov-2018 23:35:26 UTC] After insert: 478.86420440674 MB`

    Vielleicht könntet Ihr einmal über den Code schauen ich bin schon am verzweifeln.
    Update habe ich erstmal deaktiviert ( Jetpack hat mir dauernt beim löschen Objekt Fehler gebracht ) ….

    
    if ( ! class_exists( 'eln_api' ) ) :
    
    	class eln_api {
    
    		// CONNECTION SET
    		private $dealerID;
    		private $passWord;
    		private $api_base;
    
    		
    		//var
    		var $processfile;
    		var $resultCount = 100;
    		var $resultOffset = 0;
    		
    		var $search = [];
    		var $newVehicles = [];
    		var $currentVehicles = [];
    		var $modifiedVehicles = [];
    		
    		var $posts = [];
    		
    		var $message = [];
    
    		public function __construct( $dealerID, $password ){
    
    			$this->dealerID = $dealerID;
    			$this->passWord = $password;
    			$this->api_base = 'https://api.ssis.de:8443/api/dealers/';
    		}
    		
    		private function remote( $pfad, $body ){
    			
    			global $wp_version;
    			
    			$url = $this->api_base.$pfad;			
    			$args = [
    				'method' => 'POST',
    				'timeout' => 45,
                    'redirection' => 5,
                    'httpversion' => '1.0',
    				'blocking' => true,
    				'headers' => [
    					'Authorization' => 'Basic ' . base64_encode( $this->dealerID . ':' . $this->passWord ),
    					'user-agent' => 'WordPress/' .$wp_version . '; ' . home_url(),
    					'Accept-Language' => 'de-DE',
    					'content-type' => 'application/json',
    					'cache-control' => 'no-cache',
    					'charset' => 'UTF-8'],
    				'body' => json_encode( $body ),
    				'compress'	=> true,
            		'sslverify' => true ];
    			
    			$response = wp_remote_get( $url, $args );
    			
    			if ( is_wp_error( $response ) ){
    				$error_message = $response->get_error_message();
    				$this->log( $error_message );
    				$this->message['error'] = $error_message;
    				return false;
    			}
    			else{
    				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
    					$this->log( wp_remote_retrieve_response_message( $response ) );
    					$this->message['error'] = wp_remote_retrieve_response_message( $response );
    					return false;
    				}
    				
    				return wp_remote_retrieve_body( $response );
    			}
    			unset( $response );
    		}
    		
    		public function log( $message ) {
    
    			if ( WP_DEBUG_LOG === true ) {
    				if ( is_array( $message ) || is_object( $message ) ) {
    					error_log( print_r( $message, true  ));
    				}
    				else {
    					error_log( $message, 0);
    				}
    			}
    		}
    		
    		private function status ( $status ){
    
    			if( $status === true ){
    				if( file_exists( WP_PLUGIN_DIR.'/plath/admin/status/eln.pid' ) ){
    					$this->log( __( 'eln.pid is exists', 'plath') );
    					$this->message['error'] = __( 'eln.pid is exists', 'plath');
    					return false;
    			
    				}else{
    					$str_path = plugin_dir_path( __DIR__ ).'status/';
    					$this->processfile = $str_path.'eln.pid';
    					//file_put_contents("{$this->processfile}", 'run', FILE_APPEND);
    					$this->log( __( 'eln.pid was created', 'plath') );
    					$this->processfile = WP_PLUGIN_DIR.'/plath/admin/status/eln.pid';
    					return true;
    				}
    				
    			}
    			else {
    				if( file_exists( $this->processfile ) ){
    					@unlink( $this->processfile );
    					$this->log( __( 'eln.pid was deleted', 'plath') );
    					
    					return true;
    				}
    				
    			}
    		}
    		
    		protected function backspace(){
    			
    			if( file_exists( WP_PLUGIN_DIR.'/plath/admin/status/eln.pid' ) ){
    				@unlink( WP_PLUGIN_DIR.'/plath/admin/status/eln.pid' );
    			}
    		}
    		
    		public function checkCurl (){
    
    			//$data = $this->wp_remote( '/search-api/search?page.size=1' );
    					
    			//if ( !$data ){
    			//	$this->log( 'Authentification not available' );
    			//	return false;
    			//}
    			//else{
    			return true;
    			//}
    			
    			//unset( $data );
    		}
    		
    		public function dispatch(){
    			
    			$handle = empty( $_GET['handle'] ) ? '' : $_GET['handle'];
    			
    			set_time_limit(0);
    			ini_set('memory_limit', -1);
    			ignore_user_abort( true );
    			
    			switch ( $handle ) {
    					case 'import':
    						if( ! $this->import() ){ return $this->import_end(); }
    						wp_die();
    						break;
    					case 'delete':
    						if( ! $this->delete( 'delete' ) ){ return $this->import_end(); }
    						wp_die();
    						break;
    					case 'backspace':
    						$this->backspace();
    						wp_die();
    						break;
    			}
    		}
    		
    		public function import() {
    			
    			// FRAGE FAHRZEUGBESTAND AB UND SETZE STATUS FILE
    			if( ! $this->import_start() ){ return false; }
    			
    			//Turns cache invalidation on
    			wp_suspend_cache_invalidation( true );
    			
    			// CHECK EMPTY NEW VEHICLE
    			if( !empty( $this->posts )  ){
    				$this->log(__( 'Import is running', 'plath'));
    				// START IMPORT :: RESULT wp_insert_post
    				$this->process_posts( 'insert' );
    				$this->log(__( 'Import is ending', 'plath'));
    			}
    			
    			
    			//Turns cache invalidation off
    			wp_suspend_cache_invalidation( false );
    			
    			$this->import_end();
    		}
    		
    		protected function import_start() {
    			
    			// SCHREIBE PID :: RETURN true/false
    			if ( ! $this->status( true ) ){ return false; };
    			
    			// API ABFRAGE MOBILE.de SEARCH :: RETURN true/false
    			if ( ! $this->searchInfo() ){ return false; };
    			
    			// ABFRAGE ALLER NEU FAHRZEUGE :: RETURN $this-newVehicles
    			if ( ! $this->parse( 'new' ) ){ return false; };
    			
    			// ABFRAGE ALLER ALT FAHRZEUGE :: RETURN $this-currentVehicles
    			$this->parse( 'old' );
    			
    			// VERARBEITE DATEN :: RETURN $this->posts
    			$this->process();
    			
    			wp_defer_term_counting( true );
    			wp_defer_comment_counting( true );
    			
    			return true;
    			
    		}
    		
    		protected function import_end() {
    			
    			$this->clean();
    			
    			wp_cache_flush();
    			
    			wp_defer_term_counting( false );
    			wp_defer_comment_counting( false );
    			
    			// LÖSCHE PID :: RETURN true/false
    			$this->status( false );
    			
    			$this->message['success'] =  __( 'Import complete', 'plath');
    			
    			return true;
    		}
    		
    		// ABFRAGE MOBILE.de :: RETURN $this->search
    		protected function searchInfo(){
    			
    			$pfad = $this->dealerID.'/vehicles/search';
    			$body = [ 'paginationParameters'  => [ 'resultCount' => 1, 'resultOffset' => 0] ];
    			$cache = $this->remote( $pfad, $body );
    			unset( $pfad, $body );
    						
    			if ( ! $cache ){ return false; }
    			
    			$cache = json_decode( $cache, true );
    			
    			if( isset( $cache['response']['hitsFound'] ) ){
    				$this->search['total'] = $cache['response']['hitsFound'];
    				unset($cache['response']['hitsFound']);
    				unset( $cache );
    				return true;
    			}
    			
    			return false;
    			
    		}
    		
    		// LESE FAHRZEUG DATEN :: RETURN $this->newVehicles or $this->currentVehicles
    		protected function parse( $handle ){
    			
    			switch ( $handle ) {
    				case 'new':
    					
    					if( !isset( $this->search['total'] ) && empty( $this->search['total'] ) ){ return false; }
    					
    					$loop = $this->search['total']/$this->resultCount;
    					
    					//for ($i = 1; $i <= 1; $i++) {
    					for ($i = 1; $i <= ceil( $loop ); $i++) {
    						$pfad = $this->dealerID.'/vehicles/search';
    						$body = [ 'paginationParameters'  => [ 'resultCount' => $this->resultCount, 'resultOffset' => $this->resultOffset ] ];
    						$cache = $this->remote( $pfad, $body );
    						unset( $pfad, $body );
    						
    						if( ! $cache ){ return; };
    						
    						$cache = json_decode( $cache, true );
    						$ad = $cache['response']['hits'];
    						unset($cache['response']['hits'], $cache);
    						
    						foreach( $ad as $value ){
    							$this->newVehicles[] = [ 
    									'ID' => $value['vehicleId'],
    									'post_modified' => $value['dateModified'] ];
    							$clean = array_shift($ad);
    							unset($clean);
    						}
    
    						$this->resultOffset = $this->resultOffset + $this->resultCount;
    						unset( $ad );
    					}
    					
    					$this->log( __( 'New Vehicle Read', 'plath') );
    					
    					return true;
    					
    				break;
    				case 'old':
    					
    					global $wpdb;
    					
    					$sql = "SELECT {$wpdb->posts}.ID, {$wpdb->posts}.post_modified, {$wpdb->postmeta}.meta_value FROM {$wpdb->posts} INNER JOIN {$wpdb->postmeta} ON ( {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id ) INNER JOIN {$wpdb->postmeta} AS mt1 ON ( {$wpdb->posts}.ID = mt1.post_id ) WHERE 1=1  AND ( ( {$wpdb->postmeta}.meta_key = 'elnId' ) AND ( mt1.meta_key = 'api' AND mt1.meta_value = 'eln.de' ) ) AND {$wpdb->posts}.post_type = '".PLATH_INDEX."' AND ( {$wpdb->posts}.post_status = 'publish' OR {$wpdb->posts}.post_status = 'future' OR {$wpdb->posts}.post_status = 'draft' OR {$wpdb->posts}.post_status = 'pending' OR {$wpdb->posts}.post_status = 'private') GROUP BY {$wpdb->posts}.ID ORDER BY {$wpdb->posts}.post_date DESC";
    			 
    					$get_results = $wpdb->get_results($sql);
    					
    					if( $wpdb->last_error !== '' ){
    						$wpdb->print_error();
    						return;
    					}
    					
    					foreach( $get_results as $value ){
    						$this->currentVehicles[] = [ 
    							'ID' => $value->meta_value,
    							'post_id' => $value->ID,
    							'post_modified' => $value->post_modified ];
    						$clean = array_shift($get_results);
    						unset( $clean );
    					}
    					
    					wp_reset_query();
    					
    					$this->log( __( 'Old Vehicle Read', 'plath') );
    				break;	
    			}
    			
    		}
    		
    		protected function process(){
    			
    			// SIND FAHRZEUGE IN DER LISTE VORHANDEN?
    			if ( empty( $this->newVehicles )) {
    				return;
    			}	
    			
    			// $this->currentVehicles
    			// SIND FAHRZEUGE SCHON VORHANDEN?
    			if ( !empty( $this->currentVehicles ) ) {
    				
    				$currentVehicleIds = array_column( $this->currentVehicles , 'ID');
    				$this->log( count( $currentVehicleIds ) . __( ' Vehicles in Stock', 'plath') );
    				
    				$newVehicles = array_column( $this->newVehicles , 'ID');
    				// ÄNDERUNGEN CHECKEN
    				$this->checkmodifiedVehicles();
    				unset( $this->currentVehicles );
    				unset( $this->newVehicles );
    				
    				// VERGLEICHE AKTUELLE MIT NEUEN IDS
    				$soldVehicle = array_diff( $currentVehicleIds, $newVehicles );
    				
    				// FÜGE DATUMS GEÄNDERTE ID ZUM LÖSCHEN AN 
    				if( !empty( $this->modifiedVehicles ) ) {
    					$this->log( count ( $this->modifiedVehicles ).__( ' Modified Vehicle found', 'plath') );
    					$soldVehicle = array_merge( $soldVehicle, array_column( $this->modifiedVehicles , 'ID') );
    					$currentVehicleIds = array_diff( $currentVehicleIds , array_column( $this->modifiedVehicles , 'ID') );
    					unset($this->modifiedVehicles);
    				}
    		
    				// VERKAUFTE ODER GELÖSCHTE FAHRZEUGE LÖSCHEN
    				if( !empty( $soldVehicle )){
    					$soldVehicle = array_values( $soldVehicle );
    					$this->log( count( $soldVehicle ) . __( ' Vehicles to delete', 'plath') );
    					$this->delete( 'soldVehicle', $soldVehicle );
    					$this->log( __( 'Vehicles delete', 'plath') );
    				}
    				unset( $soldVehicle );
    				
    				// UPDATE POSTS 
    				/*if( !empty( $this->modifiedVehicles ) ) {
    					$this->log( count ( $this->modifiedVehicles ).__( ' Modified Vehicle found', 'plath') );
    					$this->posts = $this->modifiedVehicles;
    					unset($this->modifiedVehicles);
    					$this->process_posts( 'update' );
    					unset($this->posts);
    				}*/
    				
    				// VERGLEICHE NEUE MIT AKTUELLEN IDS
    				$cache = array_diff( $newVehicles, $currentVehicleIds );
    				$cache = array_values($cache);
    				$this->posts = $cache;
    				unset( $newVehicles, $currentVehicleIds, $cache );
    				$this->log( count( $this->posts ) . __( ' new Vehicles', 'plath') );
    				
    			}
    			else{
    
    				$this->delete( 'newImport' );
    				$this->posts = array_column( $this->newVehicles , 'ID');
    				unset( $this->newVehicles );
    				$this->log( count( $this->posts ) . __( ' Vehicle to Import', 'plath') );	
    			}	
    		}
    			
    		// DELETE VEHICLES
    		protected function delete( $handle, $ids = null ){
    			
    			switch( $handle ){
    					case 'newImport':
    						$this->deleteProcess();
    					break;
    					case 'delete':
    						// SCHREIBE PID :: RETURN true/false
    						if ( ! $this->status( true ) ){ return; };
    						
    						$this->deleteProcess();
    						
    						// LÖSCHE PID
    						$this->status( false );
    					break;
    					
    					case 'soldVehicle':
    						$this->soldVehicle( $ids );
    					break;
    			}
    			
    		}
    		
    		protected function deleteProcess(){
    			
    			$args = array(
    				'post_type'			=> array( PLATH_INDEX ),
    				'nopaging'			=> true,
    				'posts_per_page'	=> '-1',
    				'meta_query'		=> array(
    					'relation' => 'AND',
    					array(
    						'key'     => 'mobileId',
    						'compare' => 'NOT EXISTS' )),
    				'fields' 				 => 'ids',
    				'no_found_rows' 		 => true,
    				'cache_results'          => false,
    				'update_post_meta_cache' => false,
    				'update_post_term_cache' => false,
    			);
    
    			$query = new WP_Query( $args );
    			if ( $query->have_posts() ) {
    				while ( $query->have_posts() ) {
    					$query->the_post();
    					$id = get_the_ID();
    					$this->deleteImages( $id );
    					wp_delete_post ( $id, true );
    				}
    				$this->message['success'] = __( 'All Vehicles delete', 'plath');
    			} else {
    				$this->message['error'] = __( 'No vehicles found to delete', 'plath');	
    			}
    			
    			wp_reset_postdata();
    		}
    		
    		// LÖSCHE EINZELNE POSTS
    		protected function soldVehicle( $ids ){
    			
    			$args = array(
    				'post_type'			=> array( PLATH_INDEX ),
    				'nopaging'			=> true,
    				'posts_per_page'	=> '-1',
    				'meta_query'		=> array(
    					array(
    						'key'     => 'elnId',
    						'value'     => $ids,
    						'compare' => 'IN' )),
    				'fields' 				 => 'ids',
    				'no_found_rows' 		 => true,
    				'cache_results'          => false,
    				'update_post_meta_cache' => false,
    				'update_post_term_cache' => false,
    			);
    			
    			$query = new WP_Query( $args );
    		
    			if ( $query->have_posts() ) {
    				while ( $query->have_posts() ) {
    					$query->the_post();
    					$id = get_the_ID();
    					$this->deleteImages( $id );
    					wp_delete_post ( $id, true );
    				}
    			}
    			
    			wp_reset_postdata();
    		}
    		
    		protected function checkmodifiedVehicles() {
    
    			$temp_Current = [];
    			foreach( $this->currentVehicles as $value ) {
              		$temp_Current[$value['ID']] = [
    					'ID' => $value['ID'],
    					'post_id' => $value['post_id'],
    					'post_modified' => $value['post_modified']];
    				$clean = array_shift($this->currentVehicles);
    				unset($clean);
            	}
    			
    			foreach( $this->newVehicles as $value ) {
    			
    				if( isset ( $temp_Current[$value['ID']] ) ){
    		
    					$date_new = new DateTime( $value['post_modified'] );
    					$date_new->setTimezone( new DateTimeZone('Europe/Berlin') );
    				
    					$date_current = strtotime( $temp_Current[$value['ID']]['post_modified'] );
    					$date_new = strtotime( $date_new->format('Y-m-d H:i:s') );
    				
    					if ( $date_new > $date_current ){
    						$this->modifiedVehicles[] = [ 
    							'ID' => $temp_Current[$value['ID']]['ID'],
    							'post_id' => $temp_Current[$value['ID']]['post_id'], 
    						];
    					}
    				}
    				$clean = array_shift($this->newVehicles);
    				unset($clean);
    			}
    			unset( $temp_Current );
    		}
    		
    		// DELETE IMAGES
    		private function deleteImages( $id ){
    			
    			$args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => NULL, 'post_parent' => $id);
    			$attachments = get_posts($args);
    			
    			if ($attachments) {
    				foreach ($attachments as $attachment) {
    					if (wp_delete_attachment($attachment->ID, true)) {}
    					$clean = array_shift( $attachments );
    					unset($clean);
    				}
    			}
    		}
    		
    		// RÄUME AUF
    		protected function clean(){
    			/*$update_taxonomy = 'api';
    			$get_terms_args = array(
    				'taxonomy' => $update_taxonomy,
    				'fields' => 'ids',
    				'hide_empty' => false);*/
    			//$update_terms = get_terms( $get_terms_args );
    			//wp_update_term_count_now( $update_terms, $update_taxonomy );
    			
    			$this->log( __( 'Clean UP', 'plath') );
    			
    			// WP_Query arguments
    			$args = array(
    				'post_type'              => array( PLATH_INDEX ),
    				'nopaging'               => true,
    				'posts_per_page'         => '-1',
    				'orderby'                => 'id',
    				'meta_query' => array(
    					array(
    						'key'	  => 'mobileId',
    						'compare' => 'NOT EXISTS' )),
    				'fields' 				 => 'ids',
    				'no_found_rows' 		 => true,
    				'cache_results'          => false,
    				'update_post_meta_cache' => false,
    				'update_post_term_cache' => false,
    			);
    			
    			$query = new WP_Query( $args );
    			
    			$adKeys = [];
    			$postIdsToDelete = [];
    					
    			// The Loop
    			if ( $query->have_posts() ) {
    				
    				while ( $query->have_posts() ) {
    					$query->the_post();
    					$post_id = get_the_ID();
    					$meta = get_post_meta( $post_id );
    					
    					if ( !isset( $meta['complete'] ) && !isset( $meta['complete'][0] ) ) {
    						$postIdsToDelete[] = get_post_meta( $post_id, 'elnId', true );
    					}
    					
    					if ( !isset( $meta['elnId'] ) && !isset( $meta['elnId'][0] ) ) {
    						$postIdsToDelete[] = get_post_meta( $post_id, 'elnId', true );
    					}else{
    						
    						$adKey = $meta['elnId'];
    						
    						if (in_array($adKey, $adKeys)) {
    							$this->log( __( 'DUPLICATE DETECTED!', 'plath') );
    							$postIdsToDelete[] = get_post_meta( $post_id, 'elnId', true );
    						}
    						else {
    							$adKeys[] = $adKey;
    						}
    					}	
    				
    				}
    			}
    			
    			wp_reset_postdata();
    			
    			if (!empty( $postIdsToDelete )) { $this->delete( 'soldVehicle', $postIdsToDelete ); }
    			unset( $postIdsToDelete );
    		}
    		
    		// INSERT POST
    		protected function process_posts( $handle ){
    			
    			$i = 0;
    			
    			foreach( $this->posts as $id ){
    				
    				$post = new eln_api( $this->dealerID, $this->passWord );
    				$handle == 'insert' ? $post->generate( $id ) : $post->update( $id );
    				$this->log(__( 'Vehicles '.$handle, 'plath') );
    				$clean = array_shift($this->posts);
    	    		unset($post, $clean);
    				
    				if( $i % 100 == 0 ) {
    					wp_cache_flush();
    					sleep(1);
    				}
    				
    				$i++;
    				
    				$this->log( "After insert: " . ( memory_get_usage()/1048576) . " MB" .PHP_EOL );
    			}
    			unset($this->posts);
    			
    		}
    		
    		// GENERATE POST 
    		protected function generate ( $id ){
    			
    			global $wpdb;
    
    			if ( empty($id) ){
    				return;
    			}
    			
    			$elnId = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = 'elnId' and meta_value = %s", $id ) );
    			
    			if ( $elnId ) {
    				return;	
    			}
    			
    			unset($elnId);
    			
    			$format = new eln_format();
    			
    			$option = get_option('plath_eln');
    			
    			$pfad = $this->dealerID.'/vehicles/details';
    			$body = [ 'vehicleIds'  => [ $id ] ];
    			$cache = $this->remote( $pfad, $body );
    			unset( $pfad, $body );
    			
    			if( $cache === false ){ return; };
    			
    			$cache = json_decode( $cache, true );
    			
    			if ( isset( $cache['response']['vehicles'][0] )){
    			
    				$ad = $cache['response']['vehicles'][0];
    				unset( $cache );
    				
    				$basis =  __( 'Lagerwagen', 'plath' );
    				if(isset($option['basis']) && !empty( $option['basis'] )){
    					$basis = $option['basis'];
    				}
    				unset( $option );
    				
    				//array
    				$read = [];
    				$read['adKey'] = $id;
    				//<ad:ad>
    				require 'ad/ad_ad.php';
    				//<ad:vehicle>
    				require 'ad/ad_vehicle.php';
    				//<ad:ad:description>
    				//require 'ad/ad_description.php';
    				//<ad:enrichedDescription>
    				if( isset( $ad['equipment'] ) && !empty( $ad['equipment'] ) ){
    					require 'ad/ad_enrichedDescription.php';
    					unset($ad['equipment']);
    				}
    				
    				//<ad:images>
    				if( isset( $ad['images'] ) ){
    					$read['images'] = [];
    					$read['images']['api'] = 'eln';
    					require 'ad/ad_images.php';
    					unset($ad['images']);
    				}
    				
    				//<ad:price>
    				if( isset( $ad['prices'] ) ){
    					require 'ad/ad_price.php';
    					unset($ad['prices']);
    				}
    				
    				//<financing:financing>
    				//if( isset( $financing->seller ) ){
    				//	require 'ad/ad_financing.php';
    				//}
    				
    				//<seller:seller>
    				require 'ad/ad_seller.php';
    
    				if ( isset( $read['vehicle']['make'] ) ){
    					$title = $read['vehicle']['make'].' ';
    				}
    
    				if ( isset( $read['vehicle']['model'] ) && $read['vehicle']['model-description'] ){
    					$title .= $read['vehicle']['model'].' ';
    					$cache = str_ireplace( $read['vehicle']['model'], '', $read['vehicle']['model-description'] );
    					$cache = str_ireplace( $read['vehicle']['make'], '', $cache );
    					$title .= $cache;
    					unset( $cache );
    				}
    
    				$args = array(
    					'post_title' => $title,
    					'post_content' => $content,
    					'post_status' => 'Pending',
    					'comment_status' => 'closed',
    					'ping_status' => 'closed',
    					'post_type' => PLATH_INDEX,
    					'meta_input' => array(
    						'api' => __( 'eln.de', 'plath' ),
    						'basis' => $basis,
    						'elnId' => $id
    					));
    			
    				kses_remove_filters();
    
    				$post_id = wp_insert_post( $args, true );
    
    				kses_init_filters();
    			
    				if ( is_wp_error( $post_id )) {
    					$errors = $post_id->get_error_messages();
    					foreach ($errors as $error) {
    						$this->log( $error );
    					}
    					return;
    				}
    			
    				unset( $content, $basis, $format );
    
    				if( isset( $read['images']['image'] ) ){
    					$insertImages = $this->insertImages( $post_id, $read['images']['image'], $title );
    					unset($insertImages, $title );
    				}
    			
    				$api = array('api' => 'eln.de' );
    				wp_set_object_terms( $post_id, $api, 'api' );
    				unset( $api );
    			
    				if ( !isset ( $read['vehicle']['features']['EXPORT'] ) ){
    					$slider = array('slider' => 'eln.de' );
    					wp_set_object_terms( $post_id, $slider, 'slider' );
    					unset( $slider );
    				}
    
    				if( isset( $read['vehicle']['specifics']['conditions'] ) ){
    					$conditions = array('conditions' => $read['vehicle']['specifics']['conditions']);
    					wp_set_object_terms( $post_id, $conditions, 'conditions' );
    					unset( $conditions );
    				}
    
    				if( isset( $read['seller']['standort'] ) ){
    					$place = array('place' => $read['seller']['standort'] );
    					wp_set_object_terms( $post_id, $place, 'place' );
    					unset( $place );
    				}
    
    				// META
    				require( 'ad/ad_meta.php' );
    				
    				$args = array(
    					'ID' => $post_id,
    					'post_status' => 'publish',
    					'meta_input' => array(
    					'complete' => 'true',
    				));	
    				
    				$post_id = wp_update_post( $args, true );
    				if (is_wp_error($post_id)) {
    					$errors = $post_id->get_error_messages();
    					foreach ($errors as $error) {
    						$this->log( $error );
    					}
    					return;
    				}
    				
    				clean_post_cache( $post_id );
    				//wp_cache_delete( $post_id, 'posts' );
    				//wp_cache_delete( $post_id, 'post_meta' );
    			}
    		}
    		
    		// UPDATE POST 
    		protected function update ( $id ){
    			
    			if ( empty($id) ){
    				return;
    			}
    			
    			$format = new eln_format();
    			$option = get_option('plath_eln');
    			$pfad = $this->dealerID.'/vehicles/details';
    			$body = [ 'vehicleIds'  => [ $id['ID'] ] ];
    			$cache = $this->remote( $pfad, $body );
    			unset( $pfad, $body );
    			if( $cache === false ){ return; };
    			
    			$cache = json_decode( $cache, true );
    			
    			if ( isset( $cache['response']['vehicles'][0] )){
    				
    				$ad = $cache['response']['vehicles'][0];
    				unset( $cache );
    				
    				$basis =  __( 'Lagerwagen', 'plath' );
    				if(isset($option['basis']) && !empty( $option['basis'] )){
    					$basis = $option['basis'];
    				}
    				unset( $option );
    				
    				delete_post_meta( $id['post_id'], 'complete' );
    
    				// LÖSCHE BILDER
    				$this->deleteImages( $id['post_id'] );	
    
    				//array
    				$read = [];
    
    				$read['adKey'] = $id['ID'];
    
    				//<ad:ad>
    				require 'ad/ad_ad.php';
    
    				//<ad:vehicle>
    				require 'ad/ad_vehicle.php';
    
    				//<ad:ad:description>
    				//require 'ad/ad_description.php';
    
    				//<ad:enrichedDescription>
    				if( isset( $ad['equipment'] ) && !empty( $ad['equipment'] ) ){
    					require 'ad/ad_enrichedDescription.php';
    					unset($ad['equipment']);
    				}
    
    				//<ad:images>
    				if( isset( $ad['images'] ) ){
    					$read['images'] = [];
    					$read['images']['api'] = 'eln';
    					require 'ad/ad_images.php';
    					unset($ad['images']);
    				}
    
    				//<ad:price>
    				if( isset( $ad['prices'] ) ){
    					require 'ad/ad_price.php';
    					unset($ad['prices']);
    				}
    
    				//<financing:financing>
    				//if( isset( $financing->seller ) ){
    				//	require 'ad/ad_financing.php';
    				//}
    
    				//<seller:seller>
    				require 'ad/ad_seller.php';
    
    				if ( isset( $read['vehicle']['make'] ) ){
    					$title = $read['vehicle']['make'].' ';
    				}
    
    				if ( isset( $read['vehicle']['model'] ) && $read['vehicle']['model-description'] ){
    					$title .= $read['vehicle']['model'].' ';
    					$cache = str_ireplace( $read['vehicle']['model'], '', $read['vehicle']['model-description'] );
    					$cache = str_ireplace( $read['vehicle']['make'], '', $cache );
    					$title .= $cache;
    					unset( $cache );
    				}
    				
    				if( isset( $read['images']['image'] ) ){
    					$insertImages = $this->insertImages( $id['post_id'], $read['images']['image'], $title );
    					unset($insertImages);
    				}
    
    				$api = array('api' => 'eln.de' );
    				wp_set_object_terms( $id['post_id'], $api, 'api' );
    				unset( $api );
    
    				if ( !isset ( $read['vehicle']['features']['EXPORT'] ) ){
    					$slider = array('slider' => 'eln.de' );
    					wp_set_object_terms( $id['post_id'], $slider, 'slider' );
    					unset( $slider );
    				}
    
    				if( isset( $read['vehicle']['specifics']['conditions'] ) ){
    					$conditions = array('conditions' => $read['vehicle']['specifics']['conditions']);
    					wp_set_object_terms( $id['post_id'], $conditions, 'conditions' );
    					unset( $conditions );
    				}
    
    				if( isset( $read['seller']['standort'] ) ){
    					$place = array('place' => $read['seller']['standort'] );
    					wp_set_object_terms( $id['post_id'], $place, 'place' );
    					unset( $place );
    				}
    				
    				// UPDATE META
    				require( 'ad/update_meta.php' );
    			
    				$args = array(
    					'ID' => $id['post_id'],
    					'post_content' => $content,
    					'meta_input' => array(
    						'complete' => 'true',
    					));
    				
    				$post_id = wp_update_post( $args, true );
    				
    				if (is_wp_error($post_id)) {
    					$errors = $post_id->get_error_messages();
    					foreach ($errors as $error) {
    						$this->log( $error );
    					}
    					return;
    				}
    			
    				unset( $format, $title );
    			
    				clean_post_cache( $post_id );
    				//wp_cache_delete( $post_id, 'posts' );
    				//wp_cache_delete( $post_id, 'post_meta' );
    			}
    			
    			
    		}
    	
    		protected function insertImages( $post_Id, $result, $title ){
    
    			$option = get_option('plath');
    			$post_data = [];
    
    			if( isset( $option['settings']['images']) && $option['settings']['images'] == 'true' ){
    
    				foreach( $result as $data ){
    
    					foreach( $data as $url ){
    						$post_data['post_title'] = $title;
    						$saveImages = $this->saveImage( $url, $post_Id, true, md5(time().$title), $post_data );
    						$clean = array_shift($data);
    						unset($clean);
    					}
    					$clean = array_shift($result);
    					unset($clean);
    				}
    
    			}
    			else{
    				$post_data['post_title'] = $title;
    				$this->saveImage( $result[0], $post_Id, true, md5(time().$title), $post_data );
    				unset( $result, $saveImages );
    			}
    
    			unset( $option, $post_Id );
    		}
    		
    		protected function saveImage( $url = null, $post_id = null, $thumb = null, $filename = null, $post_data = array() ) {
    			
    			if ( !$url || !$post_id ) return new WP_Error('missing', "Need a valid URL and post ID...");
    			
    			require_once( ABSPATH . 'wp-admin/includes/file.php' );
    			
    			$tmp = download_url( $url );
    			
    			if ( is_wp_error( $tmp ) ) {
            		@unlink($file_array['tmp_name']);
            		$file_array['tmp_name'] = '';
            		return $tmp;
    			}
    
        		preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches);
        		$url_filename = basename($matches[0]);                                           
        		$url_type = wp_check_filetype($url_filename);                                    
    
        		if ( !empty( $filename ) ) {
            		$filename = sanitize_file_name($filename);
            		$tmppath = pathinfo( $tmp );
            		$new = $tmppath['dirname'] . "/". $filename . "." . $tmppath['extension'];
            		rename($tmp, $new);
            		$tmp = $new;
        		}
    
        		$file_array['tmp_name'] = $tmp;                                                        
    
        		if ( !empty( $filename ) ) {
            		$file_array['name'] = $filename . "." . $url_type['ext'];                           
        		} else {
    				$file_array['name'] = $url_filename;                                                
        		}
    
        		if ( empty( $post_data['post_title'] ) ) {
            		$post_data['post_title'] = basename($url_filename, "." . $url_type['ext']);
        		}
    
        		if ( empty( $post_data['post_parent'] ) ) {
            		$post_data['post_parent'] = $post_id;
    			}
    
        		require_once(ABSPATH . 'wp-admin/includes/file.php');
        		require_once(ABSPATH . 'wp-admin/includes/media.php');
        		require_once(ABSPATH . 'wp-admin/includes/image.php');
    			
        		$att_id = media_handle_sideload( $file_array, $post_id, null, $post_data );
    			
        		if ( is_wp_error($att_id) ) {
    				@unlink($file_array['tmp_name']);
            		return $att_id;
        		}
    
        		if ($thumb) {
            		set_post_thumbnail($post_id, $att_id);
        		}
    		}
    
    		public function cron (){
    
    			$option = get_option('plath_eln');
    
    			$cronTime = 'weekly';
    
    			if ( isset( $option['cron'] ) ){
    
    				$cronTime = wp_get_schedule( 'eln_periodic_event_hook' );
    			}
    
    			if ( isset($option['cron']) && $cronTime !== $option['cron']) {
    
    				$cronTime = $option['cron'];
    				wp_clear_scheduled_hook('eln_periodic_event_hook');
    			}
    
    			if ( wp_next_scheduled('eln_periodic_event_hook') ) {
    				return;
    			}
    
    			if (!wp_next_scheduled('eln_periodic_event_hook')) {
    				wp_schedule_event(time(), $cronTime, 'eln_periodic_event_hook');
    			}
    		}
    	}
    

    Lieben Dank – vielen lieben Dank –

    • Dieses Thema wurde geändert vor 1 Jahr, 3 Monate von qeib.
  • Das Thema „Import WordPress über 10.000 Posts *arg“ ist für neue Antworten geschlossen.