如何以编程方式在 WooCommerce 中添加新的自定义产品属性?

How to add NEW custom product attribute in WooCommerce programmatically?

我在网页上有一个相当大的产品数据库。该网页是用 PHP 编写的,现在我需要将其数据库迁移到 Wordpress (WooCommerce) 站点。我已经想出了如何添加产品。我用这个 header 创建了一个 php 文件(在 wordpress 之外),所以我可以使用所有 wordpress 函数:

include('../wp/wp-load.php');
require_once('../wp/wp-admin/includes/media.php');
require_once('../wp/wp-admin/includes/file.php');
require_once('../wp/wp-admin/includes/image.php');

首先,我将旧数据库中的所有产品放入 php 数组 $items,然后使用 foreach 循环遍历此数组。在循环中我有这个代码:

$user_id = get_current_user();
$post_id = wp_insert_post(array(
    'post_author' => $user_id,
    'post_title' => $item['termek'],
    'post_content' => $item['reszletes_leiras'],
    'post_status' => 'publish',
    'post_type' => "product",
));
wp_set_object_terms( $post_id, 'simple', 'product_type' );
update_post_meta( $post_id, '_visibility', 'visible' );
update_post_meta( $post_id, '_stock_status', 'instock');
update_post_meta( $post_id, 'total_sales', '0' );
update_post_meta( $post_id, '_downloadable', 'no' );
update_post_meta( $post_id, '_virtual', 'no' );
update_post_meta( $post_id, '_regular_price', $item['brutto_ar'] );
update_post_meta( $post_id, '_sale_price', $item['brutto_ar'] );
update_post_meta( $post_id, '_purchase_note', '' );
update_post_meta( $post_id, '_featured', 'no' );
update_post_meta( $post_id, '_weight', '' );
update_post_meta( $post_id, '_length', '' );
update_post_meta( $post_id, '_width', '' );
update_post_meta( $post_id, '_height', '' );
update_post_meta( $post_id, '_sku', $item['id'] );
update_post_meta( $post_id, '_product_attributes', array() );
update_post_meta( $post_id, '_sale_price_dates_from', '' );
update_post_meta( $post_id, '_sale_price_dates_to', '' );
update_post_meta( $post_id, '_price', '' );
update_post_meta( $post_id, '_sold_individually', '' );
update_post_meta( $post_id, '_manage_stock', 'no' );
update_post_meta( $post_id, '_backorders', 'no' );
update_post_meta( $post_id, '_stock', '' );

我的问题是我在 $item['parameterek'] 中也有一个数组,这看起来很糟糕:

["Some custom attribute"] => (string)"Something"
["Another custom attribute"] => (string)"Something else"

现在我需要将这些字段作为自定义属性添加到产品中。数组键是名称,值是……当然是值。我试过这样做,但这段代码似乎什么也没做:

foreach(array_keys($item['parameterek']) as $key) {
    register_attribute($key);
}
wproduct_set_attributes($post_id, $item['parameterek']);

function register_attribute($name){
    $paname = 'pa_' . htmlspecialchars(stripslashes($name));
    $permalinks = get_option('woocommerce_permalinks');
    $taxonomy_data = array(
                        'hierarchical'          => false,
                        'update_count_callback' => '_update_post_term_count',
                        'labels'                => array(
                                'name'              => $name,
                                'singular_name'     => $name,
                                'search_items'      => sprintf( __( 'Search %s', 'woocommerce' ), $label ),
                                'all_items'         => sprintf( __( 'All %s', 'woocommerce' ), $label ),
                                'parent_item'       => sprintf( __( 'Parent %s', 'woocommerce' ), $label ),
                                'parent_item_colon' => sprintf( __( 'Parent %s:', 'woocommerce' ), $label ),
                                'edit_item'         => sprintf( __( 'Edit %s', 'woocommerce' ), $label ),
                                'update_item'       => sprintf( __( 'Update %s', 'woocommerce' ), $label ),
                                'add_new_item'      => sprintf( __( 'Add New %s', 'woocommerce' ), $label ),
                                'new_item_name'     => sprintf( __( 'New %s', 'woocommerce' ), $label )
                            ),
                        'show_ui'           => false,
                        'query_var'         => true,
                        'rewrite'           => array(
                            'slug'         => empty( $permalinks['attribute_base'] ) ? '' : trailingslashit( $permalinks['attribute_base'] ) . sanitize_title( $name ),
                            'with_front'   => false,
                            'hierarchical' => 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($paname, array('product'), $taxonomy_data);
}

function wcproduct_set_attributes($post_id, $attributes) {
    $i = 0;
    // Loop through the attributes array
    foreach ($attributes as $name => $value) {
        $product_attributes[$i] = array (
            'name' => 'pa_' . htmlspecialchars(stripslashes($name)), // set attribute name
            'value' => $value, // set attribute value
            'position' => 1,
            'is_visible' => 1,
            'is_variation' => 0,
            'is_taxonomy' => 1
        );

        $i++;
    }
    update_post_meta($post_id, '_product_attributes', $product_attributes);
}

所以我的问题是:使用 PHP 从数组添加自定义产品属性的最简单方法是什么?

我最近遇到了和你一样的问题。 首先你需要考虑每个属性的选项。

is_visible 如果设置为 1 将使该属性在产品页面中可见,如果设置为 0 则仅在编辑产品页面中可见。

is_variation 用于为所述自定义属性创建相同产品的变体。如果设置为 1,则向 Woocommerce 表明存在变体,因此它将通过属性 '[= 查找与原始产品 post 相关的具有 'post_type' => "product_variation" 的 posts 45=]' 设置为原始产品 post_id like 'post_parent' => $original_post_id

is_taxonomy 用于根据所述自定义属性对产品进行分类。例如,假设衣服是要销售的产品,您可以创建一个名为性别的自定义属性来根据性别对产品进行分类。

好像在阅读您的问题,您只需要在产品页面中显示字符串值的简单自定义属性:

["Some custom attribute"] => (string)"Something"
["Another custom attribute"] => (string)"Something else"

所以实现循环的方式应该是这样的:

[loop]

$user_id = get_current_user();
$post_id = wp_insert_post(array(
    'post_author' => $user_id,
    'post_title' => $item['termek'],
    'post_content' => $item['reszletes_leiras'],
    'post_status' => 'publish',
    'post_type' => "product",
));
wp_set_object_terms( $post_id, 'simple', 'product_type' );
update_post_meta( $post_id, '_visibility', 'visible' );
update_post_meta( $post_id, '_stock_status', 'instock');
update_post_meta( $post_id, 'total_sales', '0' );
update_post_meta( $post_id, '_downloadable', 'no' );
update_post_meta( $post_id, '_virtual', 'no' );
update_post_meta( $post_id, '_regular_price', $item['brutto_ar'] );
update_post_meta( $post_id, '_sale_price', $item['brutto_ar'] );
update_post_meta( $post_id, '_purchase_note', '' );
update_post_meta( $post_id, '_featured', 'no' );
update_post_meta( $post_id, '_weight', '' );
update_post_meta( $post_id, '_length', '' );
update_post_meta( $post_id, '_width', '' );
update_post_meta( $post_id, '_height', '' );
update_post_meta( $post_id, '_sku', $item['id'] );
update_post_meta( $post_id, '_product_attributes', array() );
update_post_meta( $post_id, '_sale_price_dates_from', '' );
update_post_meta( $post_id, '_sale_price_dates_to', '' );
update_post_meta( $post_id, '_price', '' );
update_post_meta( $post_id, '_sold_individually', '' );
update_post_meta( $post_id, '_manage_stock', 'no' );
update_post_meta( $post_id, '_backorders', 'no' );
update_post_meta( $post_id, '_stock', '' );
$i = 0;
$product_attributes = array();
foreach($item['parameterek'] as $key => $value){
    $product_attributes[sanitize_title($key)] = array (
            'name' => wc_clean($key), // set attribute name
            'value' => $value, // set attribute value
            'position' => $i,
            'is_visible' => 1,
            'is_variation' => 0,
            'is_taxonomy' => 0
        );
     $i++;
}
update_post_meta($post_id, '_product_attributes', $product_attributes);
[/loop]

如果您的某个产品有变体,实施方式是,首先像您已经做的那样创建基础产品。然后将所述自定义属性保存为变体。

$attr[sanitize_title($custom_attribute_name)] = array(
     'name'=> wc_clean($custom_attribute_name),
     'value'=> $string_custom_attr_values,
     'position' => $position,
     'is_visible' => 1,
     'is_variation' => 1,
     'is_taxonomy' => 0
 );

其中 $string_custom_attr_values 是由 | 分隔的变体值组成的字符串.例如,变体尺寸的自定义属性然后 $string_custom_attr_values = 'S|M|L|XL';

然后您将需要在已有的循环中为 $items 创建一个新循环来创建所述产品的变体,类似于前面的尺寸变体示例:

$string_custom_attr_values = 'S|M|L|XL';
$arr_custom_attr_values = explode("|", $string_custom_attr_values);
$total_variations = count($arr_custom_attr_values);
$variation_post_id = $post_id;
for($i = 1; $i <= $total_variations; $i++) {
    $variation_post_id += $i;
    $variation_post = array(
        'post_title' => 'Variation #' . $variation_post_id . ' of ' . $item['termek'],
        'post_name'     => 'product-' . $variation_post_id . '-variation',
        'post_status'   => 'publish',
        'post_parent'   => $post_id,
        'post_type'     => 'product_variation',
        'guid'          =>  home_url() . '/product_variation/product-' . $variation_post_id . '-variation',
        'menu_order'    =>  $i
 );

    // Insert the variation post into the database
    $variation_post_id = wp_insert_post( $variation_post );
    update_post_meta( $variation_post_id, 'attribute_'.$custom_attribute_name, $arr_custom_attr_values[$i-1]);

    /*Rest of the post_meta like in the base product*/

}//end for

希望我说得够清楚了。