Created
May 4, 2017 20:20
-
-
Save KennyGScott/395f7781fc8199a7a947dce8c60e9cea to your computer and use it in GitHub Desktop.
Woocommerce - Change Shipping Class By Category/Categories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Couldn't find copy/paste code anywhere so I wrote it myself. The interwebz failed me. | |
| */ | |
| /** The category ID's with the posts you want to change */ | |
| $category_ids = array(48, 50, 51, 52, 53); // array of ints or single int | |
| /** The shipping class to set for the products */ | |
| $shipping_class_slug = "postcards"; // 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, | |
| '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(); |
Would be nice if you add Woocommerce version compatibility of this method. Does it work with 3.x or 4.x version of woocommerce?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent!