php - 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' ) ) ) );
}
}
}
解决方案
您可以将代码用于图像生成
$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 );
推荐阅读
- c - 如何像malloc一样使用mmap?
- json - 如何为主表和详细表发送 POST?
- django - 通用 UpdateView 不适用于 slug
- node.js - 如何修复 roblox api 请求中被拒绝的授权![Node.js] [Roblox]
- arrays - 如何将两个数组合并为一个结构
- swift - Swift:For-in 循环要求“[DeepSpeechTokenMetadata]”符合“序列”
- netsuite - 如何从套件中检索休息数据并在执行日志中打印
- html - 两种不同模型中 form.save() 的混淆
- swift - ScrollView 不使用 Geometry Reader 作为子级滚动
- python - 如何使用python更改文本文档中的特定字符?