用户选择自定义属性(责任和工作时间),然后单击购买按钮后,我试图将我的自定义商店页面重定向到购物车页面。
我已经编写了自定义JS代码,该代码检索variant_id和attributes值并将其附加到URL,以便将其自动添加到购物车并将其重定向到购物车页面。
href="yourdomain.com/?add-to-cart=47&variation_id=88&quantity=3&attribute_pa_colour=blue&attribute_pa_size=m"
这是我在博客中找到的URL格式:(https://businessbloomer.com/woocommerce-custom-add-cart-urls-ultimate-guide/)
我以这种格式创建了链接。
我的链接是:
localhost/wordpress/cart/?add-to-cart=1185&variation_id=1641&quantity=1&attribute_pa_liability=2_million&attribute_pa_hours=500_hours
在“责任”和“小时”是我的自定义属性中,其值分别为100万,200万和500小时,750小时。
但是,当重定向到购物车页面时,woocommerce给我一个错误,并显示警告框,该警告框显示错误消息为“责任和小时数为必填字段”。
我认为woocommerce无法通过我的URL获取属性值。
谁能解释这是为什么发生的,如果有的话,错误是什么?
更新
该“ Business Bloomer”指南有些过时了……您需要两件事:
1)。正确的网址
您无需将具有所有相关属性的产品和版本ID添加到购物车中。您只需要向购物车添加变体ID +您的自定义属性,如下所示:localhost/wordpress/cart/?add-to-cart=1641&quantity=1&pa_liability=2_million&pa_hours=500_hours
2)。注册(并显示)您的自定义属性:
// Store the custom data to cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_data', 10, 2 );
function save_custom_product_data( $cart_item_data, $product_id ) {
$bool = false;
$data = array();
if( isset( $_REQUEST['pa_liability'] ) ) {
$cart_item_data['custom_data']['pa_liability'] = $_REQUEST['pa_liability'];
$data['pa_liability'] = $_REQUEST['pa_liability'];
$bool = true;
}
if( isset( $_REQUEST['pa_hours'] ) ) {
$cart_item_data['custom_data']['pa_hours'] = $_REQUEST['pa_hours'];
$data['pa_hours'] = $_REQUEST['pa_hours'];
$bool = true;
}
if( $bool ) {
// below statement make sure every add to cart action as unique line item
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_variations', $data );
}
return $cart_item_data;
}
// Displaying the custom attributes in cart and checkout items
add_filter( 'woocommerce_get_item_data', 'customizing_cart_item_data', 10, 2 );
function customizing_cart_item_data( $cart_data, $cart_item ) {
$custom_items = array();
if( ! empty( $cart_data ) ) $custom_items = $cart_data;
// Get the data (custom attributes) and set them
if( ! empty( $cart_item['custom_data']['pa_liability'] ) )
$custom_items[] = array(
'name' => 'pa_liability',
'value' => $cart_item['custom_data']['pa_liability'],
);
if( ! empty( $cart_item['custom_data']['pa_hours'] ) )
$custom_items[] = array(
'name' => 'pa_hours',
'value' => $cart_item['custom_data']['pa_hours'],
);
return $custom_items;
}
代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。
经过测试和工作
您也需要将此数据添加到订单项中
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句