jondcampbell
7/15/2016 - 6:56 PM

updating data on wp all import save

updating data on wp all import save


add_action( 'pmxi_saved_post', 'sgc_post_saved', 10, 1 );

function sgc_post_saved( $post_id ) {
	// We only want to run this on import of course members
	if ( 'course-members' === get_post_type( $post_id ) ) :

		// Perform proper date formatting on our date of birth field, and passport dates
		update_date_value_of_post( $post_id, 'personal_date_of_birth' );
		update_date_value_of_post( $post_id, 'travel_passport_date_of_issue' );
		update_date_value_of_post( $post_id, 'travel_passport_date_of_expiry' );


		// Now update our course members posts order details
		$order_id = get_post_meta( $post_id ,'order_id', true );

		// Update post parent
		wp_update_post(
			array(
				'ID' => $post_id,
				'post_parent' => $order_id,
			)
		);
		// Add this course member profile to the order meta
		$course_member_ids = get_post_meta( $order_id, 'course_members_ids', true );
		if ( '' !== $course_member_ids ) :
			$course_members = explode( ', ', $course_member_ids );
			// Add another course member to the course members if there is already some
			if ( count( $course_members ) > 0 ) :
				if ( ! in_array( $post_id, $course_members ) ) :
					array_push( $course_members, $post_id );
				endif;
			endif;
		else :
			// The first one in the array
			$course_members = array( $post_id );
		endif;

		// Update the order meta
		update_post_meta( $order_id, 'course_members_ids', implode( ', ', $course_members ) );

	endif;
}

// This is used when we are updating posts just after they are imported
function update_date_value_of_post( $post_id, $field_name ){
	$old_date = get_post_meta( $post_id, $field_name, true );
	if ( ! empty( $old_date ) ) :
		// Detect if the date has slashes, otherwise we will leave it as is
		if ( strstr( $old_date, '/' ) ) :
			$dateFormat = 'd/m/Y';
			$new_date = DateTime::createFromFormat( $dateFormat, $old_date );

			update_post_meta( $post_id, $field_name, $new_date->format( 'Ymd' ) );
		endif;
	endif;
}