Last active
May 30, 2023 11:09
-
-
Save FrancoStino/e359d5e69d1669c1f0772fcbe787fe7a to your computer and use it in GitHub Desktop.
Save custom post meta into attribute and set by default attribute term into the product - Woocommerce
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 | |
/* | |
* Save custom post meta into attribute and set by default attribute term into the product - Woocommerce | |
*/ | |
function danea_produttore_meta($product_id) | |
{ | |
// Verifica se l'ordine è in fase di elaborazione | |
if (is_checkout() && !is_wc_endpoint_url('order-received')) { | |
return; | |
} | |
$taxonomy = 'pa_denominazione'; // The taxonomy | |
$term_name = get_post_meta($product_id , 'meta_easyfatt_libero_1', true); // The term "NAME" ( custom post meta ) | |
//$term_slug = sanitize_title($term_name); // The term "slug" | |
// get an instance of the WC_Product Object | |
$product = wc_get_product( $product_id ); | |
$attributes = (array) $product->get_attributes(); | |
if ( !empty($term_name) ){ | |
$attribute = new WC_Product_Attribute(); | |
$attribute->set_id( sizeof( $attributes) + 1 ); | |
$attribute->set_name( $taxonomy ); | |
$attribute->set_options( array( $term_name ) ); | |
$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', 'danea_produttore_meta', 99, 1); | |
// Save | |
$product->save(); | |
// re-hook this function | |
add_action('woocommerce_update_product', 'danea_produttore_meta', 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', 'danea_produttore_meta', 99, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment