php-在Woocommerce上的产品中设置产品类别术语

在Woocommerce中,我有一个名为“平台”的产品属性,该属性的值为“ Steam”:

php-在Woocommerce上的产品中设置产品类别术语

因此,我正在批量导入产品,并且属性已经存在.

但是现在我必须为每个产品手动设置类别.
是否可以在功能中将值自动设置为产品类别?

php-在Woocommerce上的产品中设置产品类别术语

这个函数返回我的属性值对吗?

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

这有意义吗?

解决方法:

更新2-设置产品中现有的产品类别术语(使用定义的产品ID):

// 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();
}

下面是一个挂钩函数的示例,该函数将在产品编辑时自动设置产品类别术语.

Note: the product category terms need to exist in 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文件中.它应该工作.

上一篇:php – WooCommerce – 从我的帐户页面中的菜单中删除下载


下一篇:php – 获取woocommerce购物车总金额