簡體   English   中英

如何以編程方式在WooCommerce中添加新的自定義產品屬性?

[英]How to add NEW custom product attribute in WooCommerce programmatically?

我在網頁上有一個非常大的產品數據庫。 這個網頁是用PHP編寫的,現在我需要將其數據庫遷移到Wordpress(WooCommerce)站點。 我已經想出了如何添加產品。 我用這個標題創建了一個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從數組添加自定義產品屬性的最簡單方法是什么?

我最近遇到了和你一樣的問題。 首先,您需要考慮每個屬性的選項。

如果設置為1,則is_visible將使該屬性在產品頁面中可見,並且僅在編輯產品頁面中顯示(如果設置為0)。

is_variation用於為所述自定義屬性創建相同產品的變體。 如果設置為1,則表示Woocommerce存在變體,因此它將查找與原始產品發布相關的'post_type' => "product_variation"帖子,通過屬性' post_parent '設置為原始產品post_id,'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

希望我已經足夠清楚了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM