I have some code which is programmatically creating a post using wp_insert_post.
Within the code I am setting the featured image using:
$image = "https://XXXX.com/content/uploads/2023/08/002-2.jpg";
(Note: ignore the XXXX. This URL will also be dynamic in future and will require the full https//… url path, so removing it is not an option).
When the media is saved to wordpress using wp_insert_attachment, the URL to the file duplicates the site url, for example:
https://XXXX.com/content/uploads/https://XXXX.com/content/uploads/2023/08/002-2.jpg
I am unable to find out why this is happening? My code is below, any help would be much appreciated!
PHP:
// Create Post Content
$wpdb->query( $query );
if ( !$wpdb->num_rows ) {
$post_id = wp_insert_post(
array(
'author' => $current_user_id,
'post_title' => 'test',
'post_content' => 'test content...',
'post_status' => 'draft',
'post_type' => 'post'
)
);
$image = "https://********.com/content/uploads/2023/08/002-2.jpg";
$attachment_file_type = wp_check_filetype(basename($image), null);
$wp_upload_dir = wp_upload_dir();
$attachment_args = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($image),
'post_title' => preg_replace('/.[^.]+$/', '', basename($image)),
'post_mime_type' => $attachment_file_type['type']
);
$attachment_id = wp_insert_attachment($attachment_args, $image, $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_meta_data = wp_generate_attachment_metadata($attachment_id, $image);
wp_update_attachment_metadata($attachment_id, $attachment_meta_data);
set_post_thumbnail($post_id, $attachment_id);
}
2
Answers
I checked your code. It works fine. Might be on your site exist some filters for the hooks: wp_generate_attachment_metadata or wp_update_attachment_metadata
Perhaps a function hangs on them in one of the plugins or in your site template. You can try setting the default template or disabling plugins and see if the problem persists.
Also, I recommend debugging what happened and where is coming to the wrong path:
Then you can understand where the problem appears and fix it.
You follow this code. Hope your problem will be solved.