Установите термин категории продукта в продукте на Woocommerce - PullRequest
0 голосов
/ 08 декабря 2018

В Woocommerce у меня есть атрибут продукта «Платформа». Значение атрибута «Steam»:

and then the Attribute and

Итак, я массово импортируюпродукты и атрибуты уже есть.

Но теперь я должен вручную установить для каждого продукта категорию.Можно ли автоматически установить значение в качестве категории продукта в функции?

enter image description here

Эта функция возвращает мне значение атрибута, верно?

function get_attribute_value_from_name( $name ){
  global $wpdb;
   $name = 'Platform';
    $attribute_value = $wpdb->get_var("SELECT attribute_value
     FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
  WHERE attribute_name LIKE '$name'");
 return $attribute_value;
}

А теперь, как установить значение для категории продукта?

РЕДАКТИРОВАТЬ:

$product = wc_get_product($id); //LOAD PRODUCT
global $product_attribute; //VARIABLE
$product_attribute = $product->get_attribute( 'Platform' ); //GET ATTRIBUTE OF PLATFORM
wp_set_object_terms( $post_id, $product_attribute, 'product_cat' ); //WRITE IT AS CATEGORY
$product->save();  //SAVE PRODUCT

это имеет смысл?

1 Ответ

0 голосов
/ 08 декабря 2018

Обновление 2 - для установки термина существующей категории продукта в продукте (с использованием определенного идентификатора продукта) :

// Get an instance of the WC_Product object
$product = wc_get_product( $product_id );

$term_names = $product->get_attribute( 'Platform' ); // Can have many term names (coma separated)

$term_names = explode( ',', $term_names);
$term_ids   = [];

// Loop through the terms
foreach( $term_names as $term_name ) {
    // Get the term ID and check if it exist
    if( $term_id = term_exists( $term_name, 'product_cat' ) ) {
        // Add each term ID in an array
        $term_ids[] = $term_id; 
    } 
}
// Append the product category terms in the product 
if( sizeof($term_ids) > 0 ) {
    $product->set_category_ids( $term_ids );
    $product->save();
}

Здесь нижепример подключенной функции , которая автоматически устанавливает термины категории продуктов при редактировании продукта .

Примечание: термины категории продуктов должны существовать в woocommerce

// Backend product creation
add_action( 'woocommerce_admin_process_product_object', 'add_product_category_terms_to_product', 100, 1 );
function add_product_category_terms_to_product( $product ){
    global $pagenow;

    // Only on product Edit
    if( $pagenow != 'post.php' ) return; // Exit

    if( $term_names = $product->get_attribute( 'Platform' ) ) 
        $term_names = explode( ',', $term_names);
    else
        return; // Exit

    $term_ids = [];

    // Loop through the terms
    foreach( $term_names as $term_name ) {
        // Get the term ID and check if it exist
        if( $term_id = term_exists( $term_name, 'product_cat' ) ) {
            // Add each term ID in an array
            $term_ids[] = $term_id; 
        }
    }
    // replace the product categories terms in the product 
    if( sizeof($term_ids) > 0 ) {
        $product->set_category_ids( $term_ids );
    }
    // save is not needed in the function as this hook does that
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы).Должно работать.

...