WooCommerce create new product with image from form - php

Looking to create a new product and add an image already located on the server to the media library. img.png
Currently the script creates a new product with 3 attached images but they are broken although the path appears to be correct. The new product also successfully adds to cart.
add_action('init', 'customcart');
function customcart() {
if (isset($_POST["addcustomcarts"])) {
global $woocommerce;
$my_post = array(
'post_title' => 'Nautical Product',
'post_content' => 'Desc here',
'post_status' => 'publish',
'post_author' => 1,
'post_type' =>'product'
);
// Insert the post into the database
$product_ID = wp_insert_post( $my_post );
if ( $product_ID ){
add_post_meta($product_ID, '_regular_price', 21.95 );
add_post_meta($product_ID, '_price', 21.95 );
add_post_meta($product_ID, '_stock_status', 'instock' );
$images = array('img.png', 'img.png', 'img.png');
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach($images as $name) {
$attachment = array(
'guid'=> $wp_upload_dir['url'] . 'https://example.com/' . basename( $name ),
'post_mime_type' => 'image/png',
'post_title' => 'Image name',
'post_content' => 'my description',
'post_status' => 'inherit'
);
$image_id = wp_insert_attachment($attachment, $name, $product_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 );
}
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
exit( wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ) );
}
}
}

You can put your code for image generate
$image_url = "Full path of image";
$product_id = "Product id";
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
// create correct path if not exist
if(wp_mkdir_p($upload_dir['path']))
{
$file = $upload_dir['path'] . '/' . $filename;
}
else
{
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $product_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// update attachement metadata
wp_update_attachment_metadata( $attach_id, $attach_data );
// set post thumbnail
set_post_thumbnail( $product_id, $attach_id );

Related

Image is showing in wordpress localhost uploads folder but not updating in wordpress media library (wp dashboard))

I'm trying to upload image using wp custom template in child theme but when i upload any image. It appears in "E:\Xamp\htdocs\website\wp-content\uploads\2019\10" but not uploaded to wp dashboard media library.
I'M NOT ALLOWED TO USE ANY PLUGIN FOR THIS TASK.
$post_id = wp_insert_post($my_post);
if(isset($_FILES['file']['name'])){
if(! function_exists('wp_handle_upload')){
require_once(ABSPATH.'wp-admin/includes/file.php');
}
$uploadfile = $_FILES['file'];
print_r($uploadfile);
$upload_overrides = array('test_form' => false );
$moveupload = wp_handle_upload($uploadfile,$upload_overrides);
if($moveupload && ! isset($moveupload['error'])){
echo "</Pre";
wp_update_attachment_metadata( $post_id, $moveupload);
print_r($moveupload);
echo "Post/>";
}else{
echo $moveupload['error'];
}
}
Can try out another piece of code here:
--------------------------
$upload_overrides = array( "test_form" => false );
$uploaded_file = wp_handle_upload ($file, $upload_overrides);
if( isset( $uploaded_file ["file"] )) {
$file_name_and_location = $uploaded_file ["file"];
$file_title_for_media_library = $title;
$attachment = array(
"post_mime_type" => $uploaded_file_type,
"post_title" => addslashes( $file_title_for_media_library ),
"post_content" => "",
"post_status" => "inherit"
);
if( ! is_null( $post )) {
if ( ! is_numeric( $post )) {
$post = $post->ID;
} // if ()
$attachment ['post_parent'] = $post;
} // if ()
$id = wp_insert_attachment( $attachment, $file_name_and_location );
require_once( ABSPATH."wp-admin/includes/image.php" );
$attach_data = wp_generate_attachment_metadata( $id, $file_name_and_location );
wp_update_attachment_metadata( $id, $attach_data );
} // if ()
Uploading files into the wp-content/uploads won't show up in the Media Library , those media ID's needs to be there in the database to show up in the Media Library.
If you already have files in the uploads folder and want to add them into the database
But this is not the correct solution instead fix the permissions issue for that uploads folder.
Thanks
i solved it by using custom php code.
$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
$filename = $upload['file'];
$wp_filetype = wp_check_filetype($filename, null );
// print_r($filename);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );

Doesn't add product to woocommerce from android app successfully

I want add new product to woocommerce from android app. So I wrote below code :
<?php
require_once("wp-load.php");
require_once("wp-load.php");
$image = $_POST['image'];
$name = $_POST['name'];
$info = $_POST['info'];
$price = $_POST['price'];
$saleprice = $_POST['saleprice'];
$id = $_POST['id'];
$imageName = $_POST['imageName'];
$catid = $_POST['catID'];
//add new product
$args = array(
'post_author' =>$id,
'post_content' => $info,
'post_status' => "Publish", // (Draft | Pending | Publish)
'post_title' =>$name,
'post_parent' => '',
'post_type' => "product"
);
// Create a simple WooCommerce product
$postId = wp_insert_post( $args );
//add category to new product
$cat=array($catid);
wp_set_object_terms($postId,$cat, 'product_cat');
// Setting the product type
wp_set_object_terms( $postId, 'simple', 'product_type' );
// Setting the product price
update_post_meta( $postId, '_price',$price );
if($saleprice!=null)
update_post_meta( $postId, '_sale_price', $saleprice );
// current path directory
$dirPath = getcwd();
// full path of image
$IMGFilePath = $dirPath.'/'.$imageName;
$logtxt .= $IMGFilePath. " IMGFilePathl\n";
// error message for file not found in directory
$message = $imageName.' is not available or found in directory.';
//prepare upload image to WordPress Media Library
$upload = wp_upload_bits( $imageName, null, base64_decode($image) );
// check and return file type
$imageFile = $upload['file'];
$wpFileType = wp_check_filetype($imageFile, null);
// Attachment attributes for file
$attachment = array(
'post_mime_type' => $wpFileType['type'], // file type
'post_title' => sanitize_file_name($imageFile), // sanitize and use image name as file name
'post_content' => '', // could use the image description here as the content
'post_status' => 'inherit'
);
// insert and return attachment id
$attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId );
// insert and return attachment metadata
$attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile);
// update and return attachment metadata
wp_update_attachment_metadata( $attachmentId, $attachmentData );
// finally, associate attachment id to post id
$success = set_post_thumbnail( $postId, $attachmentId );
echo $postId;
?>
I encoded image in android and send it to php file and decoded it and uploaded it in wordpress .After that I creat new peroduct .And then I Attach image to the new post. The problem is that my product is added twice and the category and image are not added correctly.
How can I fix it ?
just changed it to below code .so it worked successfully.
<?php
require_once("wp-load.php");
require_once("wp-load.php");
$image = $_POST['image'];
$name = $_POST['name'];
$info = $_POST['info'];
$price = $_POST['price'];
$saleprice = $_POST['saleprice'];
$id = $_POST['id'];
$imageName = $_POST['imageName'];
$catid = $_POST['catID'];
//add new product
$args = array(
'post_author' =>$id,
'post_content' => $info,
'post_status' => "Publish", // (Draft | Pending | Publish)
'post_title' =>$name,
'post_parent' => '',
'post_type' => "product"
);
// Create a simple WooCommerce product
$postId = wp_insert_post( $args );
//add category to new product
$cat=array($catid);
wp_set_object_terms($postId,$cat, 'product_cat');
// Setting the product type
wp_set_object_terms( $postId, 'simple', 'product_type' );
// Setting the product price
update_post_meta( $postId, '_price',$price );
if($saleprice!=null)
update_post_meta( $postId, '_sale_price', $saleprice );
$upload = wp_upload_bits( $imageName, null, base64_decode($image) );
// check and return file type
$image_url = $upload['url'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename =$imageName;
if(wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename;
else $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $postId );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$res1= wp_update_attachment_metadata( $attach_id, $attach_data );
$res2= set_post_thumbnail( $postId, $attach_id );
var_dump($res2);
?>

Set featured image using wp_insert_post

// Auto post ( Unique File Date ).
$postData = array(
'post_category' => array( $Category ),
'post_status' => $Post_Status,
'post_type' => $Post_Type
);
$post_id = wp_insert_post( $postData );
$getImageFile = 'http://localhost/Multisite/test2/wp-content/uploads/sites/4/Auto Post/twitter.png';
$attach_id = wp_insert_attachment( $postData, $getImageFile, $post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $getImageFile );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
The code above make a post successfully but it is not setting the post featured image. I don't know what I am doing wrong here.
Use different $postData for the attachment:
$wp_filetype = wp_check_filetype( $getImageFile, null );
$attachment_data = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $getImageFile ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment_data, $getImageFile, $post_id );
Currently you're passing the identical post data to the post and its attachment post.
I use the function wp_upload_bits is new WordPress function for easy for uploading image. On the second line of my code $post is your $post_id id and for upload file directory I create custom folder that is custom-uploads for your better understanding or you can remove that on my 4th line of coding that is './'. 'custom-uploads' . '/'
$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
$post_id = $posts; //set post id to which you need to set post thumbnail
$filename = $upload['file'];
$uploadfile = $uploaddir['basedir'] . '/'. 'custom-uploads' . '/';
move_uploaded_file($filename, $uploadfile); // (file name , designation)
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $posts );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id ); // set post thumnail (featured image) for the given post

set featured image after upload wordpress

i have this code which is working fine to insert the uploaded photo inside library in wordpress and it create the post successfully
but it didn't work to set the uploaded photo as featured image on the post
Note: im using custom post types.
i have try a tons of solutions on stackoverflow network and nothing work out
$dir = plugin_dir_path( __FILE__ );
$file_path = $dir."/uploads/";
$text = $_POST['text'];
$user = $_POST['usr'];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path);
$file = $file_path;
$filename = basename($file);
$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $parent_post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
unlink($file_path);
$user = get_userdatabylogin($_POST['usr']);
$user_ID = $user->ID; // prints the id of the user
global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => $_POST['text'],
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'taken_photos',
'post_category' => array(0)
);
$pid = wp_insert_post($new_post);
update_post_meta($pid, '_thumbnail_id', $attachment_id);
$attachment_data = array(
'ID' => $attachment_id,
'post_excerpt' => 'TITLE'
);
$file_path = $dir."/uploads/".date("Y")."/".date("m");
Can you please make the file path like that.Hope it will work for you.
after your line
wp_update_attachment_metadata( $attachment_id, $attachment_data );
add additional line
add_post_meta($parent_post_id, '_thumbnail_id', $attachment_id);

Wordpress - Programmatically adding products not generating thumbnails

I'm creating a custom CSV importer for a client and the pictures are added, however the thumbnails aren't being generated properly. After using a plugin like Regenerate Thumbnails they do show correctly.
Here is the code in which I add the attachment and link it to the post.
$uploadDir = 'wp-content/uploads/importedproductimages/';
$siteurl = get_option('siteurl');
$thumbnail = 'importedproductimages/' . $name;
$filename = 'importedproductimages/' . $name;
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_content' => '',
'post_status' => 'inherit',
'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$uploadDir.$name
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $thumbnail );
wp_update_attachment_metadata( $attach_id, $attach_data );
// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);
Why aren't the thumbnails being generated properly?
Thank you in advance.
EDIT:
I have also included image.php like so:
require_once(ABSPATH . 'wp-admin/includes/image.php');
This ended up working for me:
function createnewproduct($product)
{
$new_post = array(
'post_title' => $product['Product'],
'post_content' => $product['Long_description'],
'post_status' => 'publish',
'post_type' => 'product'
);
$skuu = $product['SKU'];
$post_id = wp_insert_post($new_post);
update_post_meta($post_id, '_sku', $skuu );
update_post_meta( $post_id, '_regular_price', $product['ourPrice'] );
update_post_meta( $post_id, '_manage_stock', true );
update_post_meta( $post_id, '_stock', $product['Qty'] );
update_post_meta( $post_id, '_weight', $product['Weight'] );
if (((int)$product['Qty']) > 0) {
update_post_meta( $post_id, '_stock_status', 'instock');
}
$dir = dirname(__FILE__);
$imageFolder = $dir.'/../import/';
$imageFile = $product['ID'].'.jpg';
$imageFull = $imageFolder.$imageFile;
// only need these if performing outside of admin environment
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// example image
$image = 'http://localhost/wordpress/wp-content/import/'.$product['ID'].'.jpg';
// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);
// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) && is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment->ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment->ID);
// only want one image
break;
}
}
}
}
}
Old question I know, but this came up on Google in my searches for the answer, and there is a better way to generate the thumbnails, as well as any other image sizes needed: wp_generate_attachment_meta. Used in two lines:
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
This refreshes ALL image sizes, including Thumbnails, when given an attachment ID.

Categories