insert new image into new post on frontend submit
-
I need some help on inserting new image into new post, I have a front-end submitter to add new posts but my images come from a base64_image when I submit the form both the post and the images are posted but I can’t seem to figure out how to insert the image into the post and set it as featured image also on submit
my post info is set like this
$post_information = array( 'post_title' => esc_attr(strip_tags($_POST['postTitle'])), 'post_content' => esc_attr(strip_tags($_POST['postContent'])), 'post_type' => 'product', 'post_status' => 'publish', ); $post_id = wp_insert_post( $post_information); update_post_meta( $post_id, '_regular_price', strip_tags($_POST['_regular_price'] ) ) ; update_post_meta( $post_id, '_price', strip_tags($_POST['_regular_price'] )); };and if my image is base64 it is converted and uloaded to media gallery with this code
if($_POST['base64Image'] != ''){ // Create (and CHMOD) a directory to hold temporary image files... if (!is_dir(dirname(__FILE__) . '/temp_images')){ mkdir(dirname(__FILE__) . '/temp_images/'); chmod(dirname(__FILE__) . '/temp_images/', 0777); } // Save a temporary version of the image based on the base64 supplied... define('UPLOAD_DIR', dirname(__FILE__) . '/temp_images/'); $img = $_POST['base64Image']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); // Create a $_FILES based array... $file_array['tmp_name'] = $file; $file_array['name'] = 'image.png'; // Include required files... require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // Move the file to the uploads directory... $uploadedfile = $file_array; $upload_overrides = array('test_form' => false); $movefile = wp_handle_sideload($uploadedfile, $upload_overrides); // If the move was successful... if ($movefile){ // Remove the temp image file... @unlink($file_array['tmp_name']); // Generate image metadata... $wp_filetype = wp_check_filetype(basename($movefile['file']), null); $wp_upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $movefile['file']), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($movefile['file'])), 'post_content' => '', 'post_status' => 'inherit' ); // Add the image into the media library... $attach_id = wp_insert_attachment($attachment, $movefile['file']); $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']); wp_update_attachment_metadata($attach_id, $attach_data); } }Any help will be appreciated
The topic ‘insert new image into new post on frontend submit’ is closed to new replies.