I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image "conversion". I think I can pull the old image and add it to the library using this answer. After that, I'm sort of lost.
What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.
Step 1. I need to get a pointer or id or something for the freshly added media.
I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.
Step 2. I need to make that image be part of a post.
As for how I add it to the post (in the right size) in whatever format WordPress uses natively...
I need help with both steps.
I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image "conversion". I think I can pull the old image and add it to the library using this answer. After that, I'm sort of lost.
What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.
Step 1. I need to get a pointer or id or something for the freshly added media.
I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.
Step 2. I need to make that image be part of a post.
As for how I add it to the post (in the right size) in whatever format WordPress uses natively...
I need help with both steps.
Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Dec 30, 2018 at 18:43 Matthew Brown aka Lord MattMatthew Brown aka Lord Matt 1,0683 gold badges13 silver badges34 bronze badges 4- So far I have figured out that WordPress calls this sideloading but there are several similar functions so I still need help. – Matthew Brown aka Lord Matt Commented May 6, 2019 at 1:02
- 1 Are you able to figure out the way to achieve this? If not I would like to work this problem of yours. :) – BlueSuiter Commented Jun 13, 2019 at 7:19
- I'm completely stumped at the moment. Programmatically working with posts is entirely new to me. Please feel free - I need all the help I can get. – Matthew Brown aka Lord Matt Commented Jun 13, 2019 at 7:33
- I have to look into your code, you are writing. Can you share the access to that? – BlueSuiter Commented Jun 13, 2019 at 9:28
2 Answers
Reset to default 3Hey I used this code for something similar(I was also downloading remote image and uploading to WordPress site). Please have a look:
$image_url = $value;//This is the sanitized image url.
$image = pathinfo($image_url);//Extracting information into array.
$image_name = $image['basename'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
$filename = basename($unique_file_name);
$postarr = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_type' => 'post',//or whatever is your post type slug.
'post_status' => 'publish',
'meta_input' => array(
//If you have any meta data, that will go here.
),
);
$insert_id = wp_insert_post($postarr, true);
if (!is_wp_error($insert_id)) {
if ($image != '') {
// 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, $insert_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
$thumbnail = set_post_thumbnail($insert_id, $attach_id);
}
}
Building upon the accepted answer on the linked question, I think something like this might work.
So basically,
- get the existing post content with
get_post_field
- upload the image with
wp_insert_attachment
which gives you the image ID - grab the image size and alt from the post content somehow
- let WP generate the markup for the image with
wp_get_attachment_image
- replace the old image placeholder with the new image html
- when all of the image placeholders have been replaced with img tags, save the modified post content to DB with
wp_update_post
Optionally set any of the images as the post thumbnail / featured image with set_post_thumbnail
.
$post_id = 1234;
$images = array('filename1.png', 'filename2.png', ... 'filename10.png');
// Get post content
$post_content = get_post_field( 'post_content', $post_id );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach($images as $name) {
$attachment = array(
'guid'=> $wp_upload_dir['url'] . '/' . basename( $name ),
'post_mime_type' => 'image/png',
'post_title' => 'my description',
'post_content' => 'my description',
'post_status' => 'inherit'
);
/**
* STEP 1
* add images as attachments to WordPress
*/
$image_id = wp_insert_attachment($attachment, $name, $post_id);
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $image_id, $name );
wp_update_attachment_metadata( $image_id, $attach_data );
/**
* STEP 2
* Grab image data from $post_content
*/
// strpos() + substr() maybe?
$width = 123;
$height = 123;
$alt = 'Hello';
/**
* STEP 3
* get html markup for image
*/
// Let WP generate the html markup for the image, adjust size as needed (thumbnail,medium,large,full,array(width,height))
$image_html = wp_get_attachment_image( $image_id, array( $width, $height ), false, array( 'alt' => $alt ) );
/**
* STEP 4
* Replace placeholders in content with img markup
*/
preg_replace( $pattern, $image_html, $post_content ) // I don't understand regex well enough to give an example, so you need to figure it out yourself
/**
* OPTIONAL
* set image as featured
*/
if ( $name === 'example' ) {
set_post_thumbnail( $post_id, $image_id );
}
}
/**
* STEP 5
* Update post content
*/
$post_with_imported_images = array(
'ID' => $post_id,
'post_content' => $post_content,
);
wp_update_post( $post_with_imported_images );
EDIT This should work, maybe with little tweaking, at least with the Classic Editor. I'm not sure about Gutenberg as I haven't worked with it much.