By using the code below, I can create a new post and upload an image to wordpress’s upload
directory as a attachment through a form’s submitted data.
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(3)
);
$post_id = wp_insert_post($new_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $post_id );
}
}
I want to insert an image to post, not replace the featured image so set_post_thumbnail()
function is not appropriate. I found that if I manually insert an image to post, it will generated the HTML code likes:
<a href="http://192.168.1.12/wp/wp-content/uploads/2012/09/H530U_08.jpg"><img class="alignnone size-medium wp-image-136" title="HARP_SH530U_0" src="http://192.168.1.12/wp/wp-content/uploads/2012/09/HARP_SH530U_08-300x167.jpg" alt="" width="300" height="167" /></a>
So which API would provide the function of inserting image to post, likes generating the HTML code above and not replacing the featured image?
Thanks
You can set the uploaded image as the post thumbnail via,
Example…
If you are uploading an array of images, then you might wish to specify which image by referencing the key,
…but that should not be necessary when uploading a single image.
Update:
Based on your comments, if you want to insert the image at the beggining of or before your post content its probably best you filter the
the_content
function like so,…add this function as a separate function/filter in your functions.php file. Do not try and bundle it within your
wp_insert_post
function as it will not work. This is intended to run by itself, hooking ontothe_content
filter, inserting the image at the top of the post before the content, then appending the content beneath it.This is currently running on a single post page (
is_single
) if you want it to run on something else, like a page, then change tois_page
or any other conditional tag that meets your needs.