0
我正在開發自定義功能,以便在用戶單擊帖子聯繫表單上的按鈕時以編程方式創建woocommerce產品。以下是我用來創建產品的代碼,但是我堅持通過代碼將此產品添加到購物車,因爲我無法設法在功能代碼中獲得產品ID。需要您的幫助來告訴我如何獲取產品ID以將其添加到購物車。按產品名稱獲取woocommerce產品ID
function contactform7_before_send_mail($tour_to_product) {
$tour_to_product = WPCF7_Submission::get_instance();
if ($tour_to_product) {
$formData = $tour_to_product->get_posted_data();
}
$tourprice =$formData['tour-price'];
$tourdiscountprice =$formData['tour-discount-price'];
$tourname =$formData['tour-name'];
$noadults =$formData['no-adult'];
$nochild =$formData['no-child'];
if(!empty($formData['tour-discount-price']))
{
$finalprice =$formData['tour-discount-price'];
} else {
$finalprice =$formData['tour-price'];
}
$post = array(
'post_author' => $user_id,
'post_content' => '',
'post_status' => "publish",
'post_title' => $tourname,
'post_parent' => '',
'post_type' => "product",
);
//Create post
$post_id = wp_insert_post($post, $wp_error);
if($post_id){
global $tour_id;
$attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
add_post_meta($post_id, '_thumbnail_id', $attach_id);
// i am trying here to get the product id
$tour_id = get_post_meta($product->id());
}
wp_set_object_terms($post_id, 'Tours', 'product_cat');
wp_set_object_terms($post_id, 'simple', 'product_type');
update_post_meta($post_id, '_visibility', 'visible');
update_post_meta($post_id, '_stock_status', 'instock');
update_post_meta($post_id, 'total_sales', '0');
update_post_meta($post_id, '_downloadable', 'no');
update_post_meta($post_id, '_virtual', 'yes');
update_post_meta($post_id, '_regular_price', $tourprice);
update_post_meta($post_id, '_sale_price', $tourdiscountprice);
update_post_meta($post_id, '_purchase_note', "");
update_post_meta($post_id, '_featured', "no");
update_post_meta($post_id, '_sku', "");
update_post_meta($post_id, '_product_attributes', array());
update_post_meta($post_id, '_sale_price_dates_from', "");
update_post_meta($post_id, '_sale_price_dates_to', "");
update_post_meta($post_id, '_price', $tourprice);
update_post_meta($post_id, '_sold_individually', "");
update_post_meta($post_id, '_manage_stock', "no");
update_post_meta($post_id, '_backorders', "no");
update_post_meta($post_id, '_stock', "");
// i am trying to output the product id for testing
echo "<script type='text/javascript'>alert('$tour_id')</script>";
}
remove_all_filters ('wpcf7_before_send_mail');
add_action('wpcf7_before_send_mail', 'contactform7_before_send_mail');
$ post_id = wp_insert_post($ post,$ wp_error); // <== ID – metalbox
@metalbox感謝您的回覆。您的意思是$ post_id是我正在搜索的產品ID,可用於將產品添加到購物車? –