Reputation: 31
I've read other answers about assigning category based on post tags. But can this be done based on postmeta?
I'm assuming it can be and I've been trying to change the following snippet (quoted in another answer) to achieve this. But I've had no luck tweaking it to reference postmeta meta_key (delivery_option) and meta_value (pick-up, postal, post & parcel), to then auto assign a category (pick-up, postal or post & parcel).
In case it's relevant, the above postmeta key and value have been added by another plugin.
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
// because we use save_post action, let's check post type here
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;
$tag_categories = array (
'ring' => 'Jewellery'
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
// get_terms returns ALL terms, so we have to add object_ids param to get terms to a specific product
$product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'object_ids' => $product_id ) );
foreach ($product_tags as $term) {
if ($tag_categories[$term->slug] ) {
$cat = get_term_by( 'name', $tag_categories[$term->slug], 'product_cat' );
$cat_id = $cat->term_id;
if ($cat_id) {
$result = wp_set_post_terms( $product_id, $cat_id, 'product_cat', true );
}
}
}
}
add_action('save_post','auto_add_category');
Disclosure: I'm building a WordPress website and learning as I go. This may be an obvious question, but be assured that its being asked after hours of research to try and answer myself (it's all good I've learnt other stuff while researching... just not the right stuff!). HUGE thanks in advance for any mastery insights.
Upvotes: 1
Views: 884
Reputation: 4243
This code when placed in your functions.php file will check the product's delivery option and then assign the corresponding category to the product. If any product categories for that product already exist it will append them to the list. The product category would need to exist in the first place and if it does then it assigns that category with the same slug as the delivery option. I use the hook save_post_product so that it fires only on updating products.
add_action('save_post_product', 'update_product_category', 20, 3);
function update_product_category( $post_id, $post, $update ) {
$product = wc_get_product( $post_id );
$delivery_methods = array( 'pick-up', 'postal', 'post', 'parcel' );
$delivery_option = get_post_meta($post_id, 'delivery_option', true);
if( ! empty( $delivery_option ) ) {
$product_cats = $product->get_category_ids();
foreach( $delivery_methods as $delivery_method) {
if( $delivery_option === $delivery_method ) {
$pickup_cat_id = get_term_by('slug', $delivery_method, 'product_cat')->term_id;
if( $pickup_cat_id && ! in_array( $pickup_cat_id, $product_cats) ) {
$product_cats[] = $pickup_cat_id;
$product->set_category_ids($product_cats);
$product->save();
}
}
}
}
}
Upvotes: 1