首页 > 解决方案 > WooCommerce 使用表单中的图像创建新产品

问题描述

希望创建新产品并将已位于服务器上的图像添加到媒体库。img.png

目前,该脚本创建了一个带有 3 个附加图像的新产品,但尽管路径似乎正确,但它们已损坏。新产品也成功加入购物车。

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' ) ) ) );

}

 }

}

标签: phpwordpresswoocommerce

解决方案


您可以将代码用于图像生成

$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 );

推荐阅读