Skip to content

Instantly share code, notes, and snippets.

@wpchannel
Last active February 28, 2023 07:44
Show Gist options
  • Save wpchannel/7e402a9891ec6c55b873d901e79053d0 to your computer and use it in GitHub Desktop.
Save wpchannel/7e402a9891ec6c55b873d901e79053d0 to your computer and use it in GitHub Desktop.
Custom script to import CSV file containing images into a WordPress site using Polylang as multilingual plugin.
<?php
require_once( 'wp/wp-load.php' );
// Set the path to the CSV file
$file_path = 'products_images.csv';
$count = 0;
$csv_data = array();
// Load the CSV file into an array
if ( ( $handle = fopen( $file_path, 'r' ) ) !== false ) {
while ( ( $data = fgetcsv( $handle, null, ';' ) ) !== false ) {
$args = array(
'meta_key' => 'wpc_product_id',
'meta_value' => $data[1],
'posts_per_page' => 1,
'post_type' => 'product',
'lang' => 'fr'
);
$products = new WP_Query($args);
if ($products->have_posts()) :
while ( $products->have_posts() ) : $products->the_post();
// Get the image path and filename
$image_path = $data[2];
$image_filename = basename($image_path);
if ($image_path) {
$upload_file = wp_upload_bits( $image_filename, null, file_get_contents( $image_path ) );
if ( ! $upload_file['error'] ) {
$wp_filetype = wp_check_filetype( $image_filename, null );
$attachment = [
'post_mime_type' => $wp_filetype['type'],
'post_parent' => get_the_id(),
'post_title' => $image_filename
];
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], get_the_id() );
if ( ! is_wp_error( $attachment_id ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
// return array of current image IDs
$gallery = get_field( 'field_id', get_the_ID(), false );
if ( ! $gallery ) {
$gallery = array();
}
$gallery[] = $attachment_id;
update_field( 'field_id', $gallery, get_the_ID() );
$english_post_id = pll_get_post(get_the_ID(), 'en');
update_field( 'field_id', $gallery, $english_post_id );
}
}
}
endwhile;
endif; wp_reset_postdata();
}
fclose( $handle );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment