亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

WooCommerce 使用表單中的圖像創建新產品

WooCommerce 使用表單中的圖像創建新產品

PHP
桃花長相依 2022-07-09 18:12:19
希望創建新產品并將已位于服務器上的圖像添加到媒體庫。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' ) ) ) );} }}
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

您可以將代碼用于圖像生成


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


查看完整回答
反對 回復 2022-07-09
  • 1 回答
  • 0 關注
  • 108 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號