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

时间:2019-11-19 20:15:28

标签: 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
    )

现在我已经尝试了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

}

  

此版本仅以某种方式添加了产品附带的属性,   但是它们在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 );

}

  

这似乎只是将它们添加到“产品属性标签”下   不添加条款值。

1 个答案:

答案 0 :(得分:1)

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

首先,您将需要这些帮助器功能。

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

    attribute
  2. 现在将它们应用于您的产品,我假设您正在使用每个都有变化的变量产品?父变量产品需要将其//$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; } 属性设置为属性的特殊格式数组。此函数创建该数组,如果找不到每个属性,则为它们创建全局分类法。

    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);
    }
    
  3. 我们几乎准备将属性应用于产品,但是主要的变量产品及其变体需要像任何Wordpress分类法一样为它们分配分类法术语。因此,如果您有一个名为“车轮尺寸”的分类法,且其术语为“ 28英寸”和“ 30英寸”,则母产品需要为其分配所有“ 28英寸”和“ 30英寸”术语,以及需要为其分配各自的术语,因此,一个为“ 28英寸”,另一个为“ 30英寸”。为了解决这个问题,我们使用此函数来获取和/或创建这些术语(如果不存在):

    $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);
        }
    }
    

终于可以了,现在我们可以使用以上内容将Attributes应用于我们的产品。

对于主要可变产品:

    //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!";

对于该产品的每个版本:

sleep(1)
相关问题