Wordpress Woocommerce将属性/自定义属性添加到产品中

时间:2017-05-19 15:32:58

标签: wordpress woocommerce

我有来自某些API的产品,并希望插入这些产品。我能够插入产品并使用现有属性(或通过UI添加)。

将新术语(我的颜色)添加到现有属性(颜色):

// Add term to the attribute
wp_set_object_terms( $post_id, "My Color", 'pa_color' , true );

将添加的属性与当前产品一起使用:

// Data for the term to be used
$theData = array(
                 'pa_color'=>
                    array( 
                       'name'=>'pa_color', 
                       'value'='My Color',
                       'is_visible' => '1',
                       'is_variation' => '1',
                       'is_taxonomy' => '1'
                    )
            );

// Add this attribute to this product
update_post_meta( $post_id,'_product_attributes',$theData);

如何添加新属性并将其与当前产品一起使用,例如:

RAM : 4GB

我试过这个:

register_taxonomy(
    'pa_ram',
    'product',
    array(
            'label' => __( 'RAM' ),
            'rewrite' => array( 'slug' => 'size' ),
            'hierarchical' => true,
        )
    );
}

以下是我可以在UI中看到/添加的属性的URL:

wp-admin/edit.php?post_type=product&page=product_attributes

1 个答案:

答案 0 :(得分:0)

这为我完成了这项工作:

// Insert new attribute
function process_add_attribute($attribute) {
    global $wpdb;

    if (empty($attribute['attribute_type'])) { 
        $attribute['attribute_type'] = 'select'; 
    }
    if (empty($attribute['attribute_orderby'])) { 
        $attribute['attribute_orderby'] = 'name'; 
    }
    if (empty($attribute['attribute_public'])) { 
        $attribute['attribute_public'] = 1; 
    }

    if (empty($attribute['attribute_name']) || empty($attribute['attribute_label'])) {
        return new WP_Error('error', __('Please, provide an attribute name and slug.', 'woocommerce'));
    }
    elseif(($valid_attribute_name = valid_attribute_name($attribute['attribute_name'])) && is_wp_error($valid_attribute_name)) {
        return $valid_attribute_name;
    }

    $wpdb->insert($wpdb->prefix.'woocommerce_attribute_taxonomies', $attribute);

    do_action('woocommerce_attribute_added', $wpdb->insert_id, $attribute);

    flush_rewrite_rules();
    delete_transient('wc_attribute_taxonomies');

    return true;
}

function valid_attribute_name( $attribute_name ) {
    if ( strlen( $attribute_name ) >= 28 ) {
            return new WP_Error( 'error', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
    } elseif ( wc_check_if_attribute_name_is_reserved( $attribute_name ) ) {
            return new WP_Error( 'error', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
    }

    return true;
}

称之为:

// Add new attribute
$status = process_add_attribute(array(
    'attribute_name' => 'myattribute', 
    'attribute_label' => 'My Attribute'
));
// Added successfully
if (!is_wp_error($status)) {
    // Continue 
}