有没有办法为所有产品添加默认送货类?我有一个发货类,需要一种自动方式,在创建产品时将该类添加到所有产品,而不必不断添加发货类。
答案 0 :(得分:1)
许多解决方案
有两种解决方案:
首先在购物车总数之前动态添加术语(添加到您的functions.php)
add_action('woocommerce_before_calculate_totals' , 'add_shipping_terms_before_totals' , 10, 1);
function add_shipping_terms_before_totals(WC_Cart $wc_cart){
if( count($wc_cart->get_cart()) == 0 ){
return;
}
// Here you need to edit the slug_to_edit with your custom slug
$shipping_terms = get_term_by( 'slug', 'slug_to_edit', 'product_shipping_class' );
// If can't find the terms, return
if( empty($shipping_terms) ){
return;
}
foreach( $wc_cart->get_cart() as $item){
$product = new WC_Product( $item['product_id'] );
$product_shipping_class = $product->get_shipping_class();
if( !empty($product_shipping_class) ){
continue;
}
wp_set_post_terms( $product->id, array( $shipping_terms->term_id ), 'product_shipping_class' );
}
}
或者,您可以添加一个可在添加产品时手动触发的功能:
if( isset($_GET['update_products']) && is_super_admin() ){
add_action( 'init', 'add_shipping_terms_on_all_products' );
}
function add_shipping_terms_on_all_products(){
global $wpdb;
// Here you need to edit the slug_to_edit with your custom slug
$shipping_terms = get_term_by( 'slug', 'slug_to_edit', 'product_shipping_class' );
// If can't find the terms, return
if( empty($shipping_terms) ){
return;
}
// Request all product
$products = $wpdb->get_results( "
SELECT p.ID as ID
FROM wp_posts AS p
WHERE p.post_status = 'publish'
AND p.post_type = 'product'
" );
foreach($products as $_product){
$product = new WC_Product($_product->ID);
$product_shipping_class = $product->get_shipping_class();
if( !empty($product_shipping_class) ){
continue;
}
wp_set_post_terms( $product->id, array( $shipping_terms->term_id ), 'product_shipping_class' );
}
}
然后你必须触发:
http://yoururl?update_products
作为管理员。
不要忘记使用您的运输类slug编辑slug_to_edit