0

I create plugin who create my posts from content files. My featured images are a list of urls. In CASE n ° 1, I test with a static url, the image is well imported and present in the media library (as well as the personalized title). My problem: it gets stuck in CASE 2, I call my urls file by variable but the featured image is blank in the media library. Voici une partie du code :

 $file_list_urls = $baseurlgen."imgs-urls.txt";//file path of urls images
$currentline_imgUrl = file($file_list_urls);//file in to an array

//**CASE n°1 > External url as "static" string > WORK NICELY in media library:
$image_url = "https://www.thesite.com/theimage.jpg";
//-------------------------------------------------------
//**CASE n°2 > External url from my Var > create a blank featured image in media library (custom title work) :
$image_url = $currentline_imgUrl[$number_passage];
//-------------------------------------------------------
$img_extension    = pathinfo($image_url, PATHINFO_EXTENSION);//detect image extension
$image_name       = $leadTitle.$number_passage.".".$img_extension;//Custom title > work fine in media library)
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php :
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata :
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment :
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post :
set_post_thumbnail( $post_id, $attach_id );
// update "alt" text for post :
update_post_meta($attach_id, '_wp_attachment_image_alt', $leadTitle );

Looks like wordpress doesn't interpret the $ image_url or recognize the image. I need you to understand, because here I am blocking, any idea for help please ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.