'Set shipping class based on Tag or Attribute Woocommerce
I need to update Shipping class based on Tag, example all products with tag "Fresh" shoud have shipping class "fresh" . i try this, but without results..
add_action( 'admin_init', 'action_woocommerce_init_3', 10, 1 );
function action_woocommerce_init_3( $array ) {
/** The shipping class to set for the products */
$shipping_class_slug = "fresh"; // found in "shipping classes" in woocommerce settings
/** Run query to collect our data */
$products = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'term_id',
'terms' => 'fresh',
'field' => 'slug',
'operator' => 'IN'
)
)
) );
/** Set our shipping class on each product */
foreach ($products->posts as $pid) {
wp_set_object_terms($pid, $shipping_class_slug, 'product_shipping_class');
}
/** reset the query */
wp_reset_query() ;};
I use this code for update shipping class based on category and it's working
add_action( 'admin_init', 'action_woocommerce_init', 10, 1 );
function action_woocommerce_init( $array ) {
$category_ids = array(181, 183, 1690);
$shipping_class_slug = "free";
/** Run query to collect our data */
$products = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_ids,
'operator' => 'IN'
)
)
));
/** Set our shipping class on each product */
foreach ($products->posts as $pid) {
wp_set_object_terms($pid, $shipping_class_slug, 'product_shipping_class');
}
/** reset the query */
wp_reset_query();};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|