How to add NEW custom product attribute in WooCommerce programmatically?

admin

Administrator
Staff member
I have a pretty big database of products on a webpage. This webpage was written in PHP, and now I need to migrate its database to a Wordpress (WooCommerce) site. I already figured out how to add the products. I made a php file (outside wordpress) with this header, so I can use all of the wordpress functions:

Code:
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');

First I get all products from the old database to a php array <strong>$items</strong>, and then loop through this array using a foreach loop. Inside the loop I have this code:

Code:
$user_id = get_current_user();
$post_id = wp_insert_post(array(
    'post_author' =&gt; $user_id,
    'post_title' =&gt; $item['termek'],
    'post_content' =&gt; $item['reszletes_leiras'],
    'post_status' =&gt; 'publish',
    'post_type' =&gt; "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', '' );

My problem is that I also have an array in $item['parameterek'], which looks kile this:

Code:
["Some custom attribute"] =&gt; (string)"Something"
["Another custom attribute"] =&gt; (string)"Something else"

Now I need to add these fields to the products as custom attributes. The array key is the name, and the value is... the value, of course. I tried to do it this way, but this code seems to do nothing:

Code:
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'          =&gt; false,
                        'update_count_callback' =&gt; '_update_post_term_count',
                        'labels'                =&gt; array(
                                'name'              =&gt; $name,
                                'singular_name'     =&gt; $name,
                                'search_items'      =&gt; sprintf( __( 'Search %s', 'woocommerce' ), $label ),
                                'all_items'         =&gt; sprintf( __( 'All %s', 'woocommerce' ), $label ),
                                'parent_item'       =&gt; sprintf( __( 'Parent %s', 'woocommerce' ), $label ),
                                'parent_item_colon' =&gt; sprintf( __( 'Parent %s:', 'woocommerce' ), $label ),
                                'edit_item'         =&gt; sprintf( __( 'Edit %s', 'woocommerce' ), $label ),
                                'update_item'       =&gt; sprintf( __( 'Update %s', 'woocommerce' ), $label ),
                                'add_new_item'      =&gt; sprintf( __( 'Add New %s', 'woocommerce' ), $label ),
                                'new_item_name'     =&gt; sprintf( __( 'New %s', 'woocommerce' ), $label )
                            ),
                        'show_ui'           =&gt; false,
                        'query_var'         =&gt; true,
                        'rewrite'           =&gt; array(
                            'slug'         =&gt; empty( $permalinks['attribute_base'] ) ? '' : trailingslashit( $permalinks['attribute_base'] ) . sanitize_title( $name ),
                            'with_front'   =&gt; false,
                            'hierarchical' =&gt; true
                        ),
                        'sort'              =&gt; false,
                        'public'            =&gt; true,
                        'show_in_nav_menus' =&gt; false,
                        'capabilities'      =&gt; array(
                            'manage_terms' =&gt; 'manage_product_terms',
                            'edit_terms'   =&gt; 'edit_product_terms',
                            'delete_terms' =&gt; 'delete_product_terms',
                            'assign_terms' =&gt; '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 =&gt; $value) {
        $product_attributes[$i] = array (
            'name' =&gt; 'pa_' . htmlspecialchars(stripslashes($name)), // set attribute name
            'value' =&gt; $value, // set attribute value
            'position' =&gt; 1,
            'is_visible' =&gt; 1,
            'is_variation' =&gt; 0,
            'is_taxonomy' =&gt; 1
        );

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

So my question is: What is the easiest way to add custom product attributes from an array using PHP?