Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/41220f4d565f3856fc0a7333c3f71cef to your computer and use it in GitHub Desktop.
Save FrancoStino/41220f4d565f3856fc0a7333c3f71cef to your computer and use it in GitHub Desktop.
Save custom post meta into attributes and set by default multiple attribute term into the product - Woocommerce
<?
/*
* Save custom post meta into attributes and set by default multiple attribute term into the product - Woocommerce
*/
function update_post_meta_subito($product_id)
{
$taxonomy = 'pa_brand'; // The taxonomy
$term_name = get_post_meta($product_id, 'meta_product_producer', true); // Custom post meta
// $term_slug = sanitize_title($term_name); // The term "slug"
$term_id = $term_name;
// get an instance of the WC_Product Object
$product = wc_get_product($product_id);
$attributes = (array)$product->get_attributes();
// 1. If the product attribute is set for the product
if (array_key_exists($taxonomy, $attributes))
{
foreach ($attributes as $key => $attribute)
{
if ($key == $taxonomy)
{
$options = (array)$attribute->get_options();
$options[] = $term_id;
$attribute->set_options($options);
$attributes[$key] = $attribute;
break;
}
}
$product->set_attributes($attributes);
}
// 2. The product attribute is not set for the product
else
{
$attribute = new WC_Product_Attribute();
$attribute->set_id(sizeof($attributes) + 1);
$attribute->set_name($taxonomy);
$attribute->set_options(array(
$term_id
));
$attribute->set_position(sizeof($attributes) + 1);
$attribute->set_visible(true);
$attribute->set_variation(false);
$attributes[] = $attribute;
$product->set_attributes($attributes);
}
//If calling wp_update_post, unhook this function so it doesn't loop infinitely
remove_action('woocommerce_update_product', 'update_post_meta_subito', 99, 1);
// Save
$product->save();
// re-hook this function
add_action('woocommerce_update_product', 'update_post_meta_subito', 99, 1);
// Append the new term in the product
if (!has_term($term_name, $taxonomy, $product_id)) wp_set_object_terms($product_id,/* $term_slug,*/ $taxonomy, true);
}
add_action('woocommerce_update_product', 'update_post_meta_subito', 99, 1);
/* --- */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment