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);
?>
Related
I am a beginner in PHP development and I am creating a script to process products from a CSV file.
I manage to import everything, except the images which cause problems because there are several in the same entry.
Regardless of this issue I have searched everywhere for a way to attach these images to each WooCommerce product's gallery but found no satisfying answer.
Finally I already manage to send to insert these featured images for each product. could you help me ?
Here's my code:
// Get and insert featured product image in database
function generate_Featured_Image( $image_url, $post_id ){
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
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, $post_id );
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( $post_id, $attach_id );
}
foreach ($items as $item) {
$title = array_key_exists(2, $item) ? $item[2] : null;
$description = array_key_exists(3, $item) ? $item[3] : null;
// Multiple images in each key
$img = array_key_exists(4, $item) ? $item[4] : null;
$images = explode(';', $img);
$cat = array_key_exists(5, $item) ? $item[5] : null;
$price = array_key_exists(8, $item) ? $item[8] : null;
$stock = array_key_exists(6, $item) ? $item[6] : null;
array_unshift($images, $title, $description, $cat, $price, $stock);
array_filter($images);
$postarr = array(
'post_title' => wp_strip_all_tags($title),
'post_name' => $title,
'post_content' => $description,
'post_type' => 'product',
'post_status' => 'publish',
);
$insert_id = wp_insert_post($postarr, true);
foreach ($images as $ru) {
$sol = 'https://static.wixstatic.com/media/';
$sol .= $ru;
generate_Featured_Image($sol, $insert_id);
}
wp_set_object_terms($insert_id, $category, 'product_cat');
//set product type
wp_set_object_terms($insert_id, 'simple', 'product_type');
update_post_meta( $insert_id, '_price', $price );
update_post_meta($insert_id, '_sku', $stock);
update_post_meta($insert_id, 'total_sales', '0');
}
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 );
I am working on migrate blog posts, which are more than 1000 posts, from an old custom database website to wordpress. After formatted each post with php array, I am testing how to migrate them to wordpress.
What I want to do is migrate blog posts with featured images. After some research, I used wp_insert_post() which worked just with the text contents> However it does not insert featured images, so I need to use wp_insert_attachnment() as well. The problem is when I use wp_insert_post() and wp_insert_attachnment() together, inside foreach loop, it does not work well. The code I have is below. If anyone has knowledge/approach about this issue, please give me advice. Thank you.
$wp_posts = array(
array(
'post_id' => '10',
'post_title' => 'Post Title 1',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 1',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image1.jpg'
),
array(
'post_id' => '11',
'post_title' => 'Post Title 2',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 2',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image2.jpg'
)
);
$filetype['type'] = 'image/jpeg';
$last = count($wp_posts) - 1;
foreach ($wp_posts as $i => $row){
$ID = $row['post_id'];
$title = $row['post_title'];
$content = $row['post_content'];
$postdate = $row['post_date']. " 12:00:00";
$imagePath = $row['post_imagePath'];
if (!get_page_by_title($title, 'OBJECT', 'post') ){
$my_post = array(
'ID' => $ID,
'post_title' => $title,
'post_content' => $content,
'post_date' => $postdate,
);
wp_insert_post( $my_post );
/* wp_insert_attachment */
$filetype = wp_check_filetype( basename( $imagePath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $imagePath ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $imagePath ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $imagePath, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
/* ./wp_insert_attachment */
}
}
Do not add the ID when using wp_insert_post(), this will try and update an entry with that ID.
IMPORTANT: Setting a value for $post['ID'] WILL NOT create a post with
that ID number. Setting this value will cause the function to update
the post with that ID number with the other values specified in $post.
In short, to insert a new post, $post['ID'] must be blank or not set
at all.
wp_insert_post() documentation
Also make sure the post has actually been inserted before continuing your script. eg
$post_id = wp_insert_post( $my_post );
if(!$post_id) {
//log an error or something...
continue;
}
Haven't test it but i think this will do it.
foreach ($wp_posts as $i => $row){
$ID = $row['post_id'];
$title = $row['post_title'];
$content = $row['post_content'];
$postdate = $row['post_date']. " 12:00:00";
$imagePath = $row['post_imagePath'];
$my_post = array(
'ID' => $ID,
'post_title' => $title,
'post_content' => $content,
'post_date' => $postdate,
);
$parent_post_id = wp_insert_post( $my_post ); //Returns the post ID on success.
/**** wp_insert_attachment ****/
$filetype = wp_check_filetype( basename( $imagePath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name(basename($image_url)),
'post_content' => '',
'post_status' => 'inherit'
);
// So here we attach image to its parent's post ID from above
$attach_id = wp_insert_attachment( $attachment, $imagePath, $parent_post_id);
// Attachment has its ID too "$attach_id"
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
$res1= wp_update_attachment_metadata( $attach_id, $attach_data );
$res2= set_post_thumbnail( $parent_post_id, $attach_id );
}
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);
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.