Woocommerce 以编程方式添加产品属性及其对应的值

Joh*_*Doe 2 wordpress woocommerce

我正在构建一个获取产品的脚本,我被困在以编程方式添加属性的部分。所以基本上我想检查一个属性是否存在,如果不存在则添加它。然后检查它的价值是否存在,如果不存在,他们添加它的价值,并将所有东西附加到我的产品上。

这是我获得产品的格式:

 [attributes] => Array
(
[0] => stdClass Object
    (
        [id] => 332
        [name] => Gender
        [value] => Woman
    )

[1] => stdClass Object
    (
        [id] => 333
        [name] => Wheel Size
        [value] => 28 Inch
    )

[2] => stdClass Object
    (
        [id] => 334
        [name] => Frame height
        [value] => 56 cm
    )
Run Code Online (Sandbox Code Playgroud)

现在我已经尝试了 2 个版本,我将粘贴两个代码示例。

版本 1:

foreach($product->attributes as $attribute) {
$slug = 'pa_' . strtolower($attribute->name);
$attribute_name = $attribute->name;
$attribute_value = $attribute->value;

$permalinks = get_option( 'woocommerce_permalinks' );

$taxonomy_data = array(
                    'hierarchical'          => true,
                    'update_count_callback' => '_update_post_term_count',
                    'labels'                => array(
                            'name'              => $attribute_name
                        ),
                    'show_ui'           => false,
                    'query_var'         => true,
                    'sort'              => false,
                    'public'            => true,
                    'show_in_nav_menus' => false,
                    'capabilities'      => array(
                        'manage_terms' => 'manage_product_terms',
                        'edit_terms'   => 'edit_product_terms',
                        'delete_terms' => 'delete_product_terms',
                        'assign_terms' => 'assign_product_terms',
                    )
                );

register_taxonomy( $slug, array('product'), $taxonomy_data );
// @end_Debug
Run Code Online (Sandbox Code Playgroud)

}

此版本仅添加了以某种方式附加到产品的属性,但它们在 Wordpress Admin 的“属性”选项卡下不可见。稍后我希望通过这些属性进行过滤,因此我需要与 Woocommerce 属性的连接。


版本 2:

foreach($product->attributes as $attribute) {
$slug = 'pa_' . strtolower($attribute->name);
$attribute_name = $attribute->name;
$attribute_value = $attribute->value;
$table = $wpdb->prefix . 'woocommerce_attribute_taxonomies';

$attr = $wpdb->get_results( "SELECT * FROM {$table} WHERE attribute_name LIKE '%{$attribute_name}%'", OBJECT );
if(count($attr) > 0) {
    //
}
else {
    /** create taxonomy */
    $data = array(
        'attribute_label'   => $attribute_name,
        'attribute_name'    => $slug,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0, // Enable archives ==> true (or 1)
    );

    $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );

    if ( is_wp_error( $results ) ) {
        return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
    }

    $id = $wpdb->insert_id;

    do_action('woocommerce_attribute_added', $id, $data);

    wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
    /* end_Create */
}


// Clean attribute name to get the taxonomy
$taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_name );

$option_term_ids = array(); // Initializing

// Loop through defined attribute data options (terms values)
if( term_exists( $attribute_value, $taxonomy ) ){
    // Save the possible option value for the attribute which will be used for variation later
    wp_set_object_terms( $product_id, $attribute_value, $taxonomy, true );
    // Get the term ID
    $option_term_ids[] = get_term_by( 'name', $attribute_value, $taxonomy )->term_id;
}

    // Loop through defined attribute data
$attributes[$taxonomy] = array(
    'name'          => $taxonomy,
    'value'         => $option_term_ids, // Need to be term IDs
    'position'      => '1',
    'is_visible'    => '1',
    'is_variation'  => '1',
    'is_taxonomy'   => '1'
);

// Save the meta entry for product attributes
update_post_meta( $product_id, '_product_attributes', $attributes );
Run Code Online (Sandbox Code Playgroud)

}

这个似乎只在产品属性选项卡下添加它们,也没有添加术语值。

Mik*_*ote 9

好的,这是一项相当复杂的任务,但这是我通过查看其他人的源代码并根据需要进行修改而得到的代码。

首先,您将需要这些辅助函数。

  1. 要创建全局属性,您需要使用以下函数为每个属性(性别、车轮尺寸等)创建一个分类法:

    function create_global_attribute($name, $slug)
    {
    
        $taxonomy_name = wc_attribute_taxonomy_name( $slug );
    
        if (taxonomy_exists($taxonomy_name))
        {
            return wc_attribute_taxonomy_id_by_name($slug);
        }
    
        //logg("Creating a new Taxonomy! `".$taxonomy_name."` with name/label `".$name."` and slug `".$slug.'`');
    
        $attribute_id = wc_create_attribute( array(
            'name'         => $name,
            'slug'         => $slug,
            'type'         => 'select',
            'order_by'     => 'menu_order',
            'has_archives' => false,
        ) );
    
        //Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
        register_taxonomy(
            $taxonomy_name,
            apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy_name, array( 'product' ) ),
            apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy_name, array(
                'labels'       => array(
                    'name' => $name,
                ),
                'hierarchical' => true,
                'show_ui'      => false,
                'query_var'    => true,
                'rewrite'      => false,
            ) )
        );
    
        //Clear caches
        delete_transient( 'wc_attribute_taxonomies' );
    
        return $attribute_id;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 现在要将这些应用于您的产品,我假设您正在使用每个都有变化的可变产品?父变量产品需要将其attribute属性设置为特殊格式的属性数组。此函数创建该数组,如果未找到,则为每个属性创建全局分类法。

    //$rawDataAttributes must be in the form of array("Color"=>array("blue", "red"), "Size"=>array(12,13,14),... etc.)
    function generate_attributes_list_for_product($rawDataAttributes)
    {
        $attributes = array();
    
        $pos = 0;
    
        foreach ($rawDataAttributes as $name => $values)
        {
            if (empty($name) || empty($values)) continue;
    
            if (!is_array($values)) $values = array($values);
    
            $attribute = new WC_Product_Attribute();
            $attribute->set_id( 0 );
            $attribute->set_position($pos);
            $attribute->set_visible( true );
            $attribute->set_variation( true );
    
            $pos++;
    
            //Look for existing attribute:
            $existingTaxes = wc_get_attribute_taxonomies();
    
            //attribute_labels is in the format: array("slug" => "label / name")
            $attribute_labels = wp_list_pluck( $existingTaxes, 'attribute_label', 'attribute_name' );
            $slug = array_search( $name, $attribute_labels, true );
    
            if (!$slug)
            {
                //Not found, so create it:
                $slug = wc_sanitize_taxonomy_name($name);
                $attribute_id = create_global_attribute($name, $slug);
            }
            else
            {
                //Otherwise find it's ID
                //Taxonomies are in the format: array("slug" => 12, "slug" => 14)
                $taxonomies = wp_list_pluck($existingTaxes, 'attribute_id', 'attribute_name');
    
                if (!isset($taxonomies[$slug]))
                {
                    //logg("Could not get wc attribute ID for attribute ".$name. " (slug: ".$slug.") which should have existed!");
                    continue;
                }
    
                $attribute_id = (int)$taxonomies[$slug];
            }
    
            $taxonomy_name = wc_attribute_taxonomy_name($slug);
    
            $attribute->set_id( $attribute_id );
            $attribute->set_name( $taxonomy_name );
            $attribute->set_options($values);
    
            $attributes[] = $attribute;
        }
    
    
        return $attributes;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我们几乎已准备好将属性应用于产品,但主要的变量产品及其变体需要像任何 Wordpress 分类法一样为它们分配分类术语。因此,如果您有一个名为“车轮尺寸”的分类法,其中包含术语“28 英寸”和“30 英寸”,那么父产品需要分配所有“28 英寸”和“30 英寸”术语,以及变体需要为他们分配各自的术语,因此一个为“28 英寸”,另一个为“30 英寸”。为了解决这个问题,我们使用这个函数来获取和/或创建这些不存在的术语:

    function get_attribute_term($value, $taxonomy)
    {
        //Look if there is already a term for this attribute?
        $term = get_term_by('name', $value, $taxonomy);
    
        if (!$term)
        {
            //No, create new term.
            $term = wp_insert_term($value, $taxonomy);
            if (is_wp_error($term))
            {
                //logg("Unable to create new attribute term for ".$value." in tax ".$taxonomy."! ".$term->get_error_message());
                return array('id'=>false, 'slug'=>false);
            }
            $termId = $term['term_id'];
            $term_slug = get_term($termId, $taxonomy)->slug; // Get the term slug
        }
        else
        {
            //Yes, grab it's id and slug
            $termId = $term->term_id;
            $term_slug = $term->slug;
        }
    
        return array('id'=>$termId, 'slug'=>$term_slug);
    }
    
    Run Code Online (Sandbox Code Playgroud)

好的,现在我们可以使用上面的方法将 Attributes 应用到我们的产品中。

对于主要可变产品:

$yourRawAttributeList = array("Gender" => array("Woman", "Man"), "Wheel Size" => array("28 Inch","30 Inch","32 Inch"));
$attribs = generate_attributes_list_for_product($yourRawAttributeList);

$p = new WC_Product_Variable($postID);

$p->set_props(array(
    'attributes'        => $attribs,
    //Set any other properties of the product here you want - price, name, etc.
));

$postID = $p->save();

if ($postID <= 0) return "Unable to create / update product!";

//Attribute Terms: These need to be set otherwise the attributes dont show on the admin backend:
foreach ($attribs as $attrib)
{
    /** @var WC_Product_Attribute $attrib */
    $tax = $attrib->get_name();
    $vals = $attrib->get_options();

    $termsToAdd = array();

    if (is_array($vals) && count($vals) > 0)
    {
        foreach ($vals as $val)
        {
            //Get or create the term if it doesnt exist:
            $term = get_attribute_term($val, $tax);

            if ($term['id']) $termsToAdd[] = $term['id'];
        }
    }

    if (count($termsToAdd) > 0)
    {
        wp_set_object_terms($postID, $termsToAdd, $tax, true);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于该产品的每个变体:

    //This is an array of input attributes in the form: array("Color"=>"Navy", "Size"=>"25")
$theseAttributes = array("Gender" => array("Woman"), "Wheel Size" => array("28 Inch"));

//This is the final list of attributes that we are calculating below.
$theseAttributesCalculated = array();

//logg("Want to add these attributes to the variation: ".print_r($theseAttributes, true));

$existingTax = wc_get_attribute_taxonomies();

foreach ($theseAttributes as $name => $value)
{
    if (strlen($name) == 0 || strlen($value) == 0)
    {
        //logg("Attribute array had a blank value for product variant ".$sku.': '.print_r($theseAttributes, true));
        return "Attribute array had a blank value.";
    }

    $tax = '';
    $slug = '';

    //Look for an existing taxonomy to match this attribute's $name
    //$thistax->attribute_name = slug of the taxonomy
    //$thistax->attribute_label = name of the taxonomy

    foreach ($existingTax as $thistax)
    {
        if ($thistax->attribute_label == $name)
        {
            $slug = $thistax->attribute_name;
            $tax = wc_attribute_taxonomy_name($slug);
            break;
        }
    }

    if (empty($tax))
    {
        $slug = wc_sanitize_taxonomy_name($name);
        //Taxonomy not found, so create it...
        if (create_global_attribute($name, $slug) > 0)
        {
            $tax = wc_attribute_taxonomy_name($slug);
        }
        else
        {
            //logg("Unable to create new attribute taxonomy ".$slug." for attribute ".$name."found in variable product ".$sku);
            continue;
        }
    }


    //logg("Want to add attribute ".$name. " value ".$value. " which is term ".$term_slug." (".$termId.") to post ".$parentID);

    $term = get_attribute_term($value, $tax);


    if ($term['id'])
    {
        // Set/save the attribute data in the product variation
        $theseAttributesCalculated[$tax] = $term['slug'];
    }
    else
    {
        //logg("Warning! Unable to create / get the attribute ".$value." in Taxonomy ".$tax);
    }
}

//logg("Finished gathering. Results: ".print_r($theseAttributesCalculated, true));


$variation  = new \WC_Product_Variation($postID);

$variation->set_props( array(
    'attributes'        => $theseAttributesCalculated,
));

$postID = $variation->save();

if ($postID <= 0) return "Unable to create product variation!";
Run Code Online (Sandbox Code Playgroud)

  • 我们能否花一点时间来了解一下完成一些相对简单的事情需要多少自定义代码!令人惊讶的是,2022 年还没有为此提供辅助方法。 (3认同)
  • 感谢您的深入回答。这里有很多好东西。 (2认同)