【发布时间】:2021-02-18 17:06:46
【问题描述】:
我已经为产品存档页面构建了自定义Buy Now 按钮,使用以下 URL 结构将产品添加到购物车:
www.mydomain.com/shop/?add-to-cart=30 <-product ID
效果很好,但我需要使用钩子 woocommerce_add_cart_item_data 并且该钩子不响应我的 URL 请求。
这是我尝试过的:
// Save the "grams_quantity" custom product field data in Cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_in_cart_the_custom_product_field', 10, 2 );
function save_in_cart_the_custom_product_field( $cart_item_data, $product_id ) {
if( isset( $_POST['grams_quantity'] ) ) {
$cart_item_data[ 'grams_quantity' ] = $_POST['grams_quantity'];
// When add to cart action make an unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $_POST['grams_quantity'] );
}
return $cart_item_data;
}
该代码在single-product.php 页面中运行良好,因为那里的按钮不是自定义的。
这是我将自定义字段添加到存档商店产品循环的方式:
// Add a product custom field "grams_quantity" that will update the displayed price
add_action('woocommerce_after_shop_loop_item', 'custom_shop_loop', 30);
function custom_shop_loop(){
// get the current post/product ID
$product_id = get_the_ID();
// get the product based on the ID
$product = wc_get_product( $product_id );
if( $product->is_type( 'simple' ) ){
// Only for products under certain category
if ( ! ( has_term( 'מגשי פירות', 'product_cat', $product_id ) ) ) return;
?>
<div class="grams-field">
<label for="grams_quantity"><?php _e('גרמים: ','woocoomerce'); ?><span></span><br>
<input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">
</label>
</div><br>
<?php
}
}
现在当我点击 Buy Now 按钮时,它会将我的产品添加到购物车而没有 grams_quantity 数据属性。
如何在存档商店页面中正确使用woocommerce_add_cart_item_data 挂钩?
编辑:
【问题讨论】:
-
@LoicTheAztec 有没有办法或指南来解释我应该如何执行?我不太确定我能在这里做什么..
-
@LoicTheAztec 我明白,虽然我无法弄清楚 ajax 是如何相关的,因为
woocommerce_add_cart_item_data是基于$_POST不是从我的single-product.php页面中的ajax 获得的,它只是刷新 DOM 以获取$_POST。 -
@LoicTheAztec 从逻辑上讲,不能得到克值,也很容易被滥用..我显然必须使用
$_POST -
对不起,我不太明白,看来您的主题或您自己已经进行了一些不使用 WooCommerce 默认行为的自定义。对于提供的代码和信息,我无能为力。
-
@LoicTheAztec 我在我的问题中添加了 codepen 来分享我的整个代码,基本上相关的是顶部。我真的迷路了,它应该按逻辑工作。
标签: php wordpress woocommerce