我的电子商务是这样运作的:我有一些可下载的产品,其中有一个文件列表附加到它,可供下载。
但是,我需要过滤器的下载根据用户将添加到购物车时所作的选择。需要存储这些选项,以便根据所选选项对客户可用的下载进行 * 筛选 *。因此,将下载文件的名称与数组中的字符串进行比较就可以了。
示例:下载产品包含名为Weight 1、Weight 2、Weight 3等的下载。用户在添加到购物车时选择Weight 1和Weight 3。用户只获取这些文件,称为Weight 1和Weight 3。
到目前为止,这些选择已成功地存储到产品项Meta数据中作为字符串数组。在 functions.php 中使用以下函数:
// save selected weights into meta for minicart
add_filter( 'woocommerce_add_cart_item_data', 'save_font_weights', 10, 3 );
function save_font_weights( $cart_item_data, $product_id, $variation_id ) {
$fw = $_POST['font_weights'];
if( !empty($fw) ) {
$cart_item_data[ 'selected_font_weights' ] = $fw;
// below statement make sure every add to cart action as unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'session_fw', $fw );
}
return $cart_item_data;
}
// output custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_font_weights', 10, 2 );
function output_font_weights( $cart_data, $cart_item ) {
if( isset( $cart_item['selected_font_weights'] ) ) {
$cart_data[] = array(
'key' => __('Selected weights', 'woocommerce'),
'value' => $cart_item['selected_font_weights'],
'display' => $cart_item['selected_font_weights'],
);
}
return $cart_data;
}
// save cart item custom meta as order item meta data and display it everywhere on orders and email notifications.
add_action( 'woocommerce_checkout_create_order_line_item', 'save_weights_to_order', 10, 4 );
function save_weights_to_order( $item, $cart_item_key, $values, $order ) {
if( isset($values['selected_font_weights']) && ! empty($values['selected_font_weights']) ) {
$item->update_meta_data( 'Selected weights', $values['selected_font_weights']);
}
$product_id = $item['product_id'];
$w = get_post_meta( $product_id, 'selected_font_weights', true );
wc_add_order_item_meta($item, 'Selected weights', $w , true);
}
通过这种方式,数据可以一直访问到“订单已收到”页面。我现在正在努力的是过滤此页面和电子邮件中的下载内容等。根据是否有一个钩子通过比较文件名和数组中列出的字符串来过滤下载?
1条答案
按热度按时间siv3szwd1#
你的代码中有一些错误和不必要的东西。请使用以下选项:
下面我使用2个新的功能,除了现有的代码:
$some_variable_to_replace
,以便与所选权重数组进行比较注意:在最后一个函数中,我首先列出了您可以从每个下载项目中获取的所有数据,并将其放入您可以使用的变量中。
附加功能:
代码放在子主题的functions.php文件中(或插件中)。应该可以的