首页 > 解决方案 > 如何使用 WooCommerce Core 在新产品上设置自定义产品元?

问题描述

我正在使用 PHP 向我的 WooCommerce 商店批量添加新产品(汽车列表)。我正在遍历自定义数据表中的行并将它们添加为 WooCommerce 产品。

我能够保存每个产品并添加默认元数据(即描述、价格、sku、可见性等)。但是,我无法设置自定义产品元。我这样做的顺序错误吗?

下面是我的 FOREACH 循环中保存每一行的代码(但“set_meta_data”不起作用)。

foreach ( $cars as $car ) {
    set_time_limit(60);

    $product = new WC_Product_Simple();
    $product->set_name( $car->heading );
    $product->set_status( 'publish' );
    $product->set_slug( $car->heading . '-' . uniqid() );
    $product->set_description( $car->seller_comments );
    $product->set_regular_price( $car->price );
    $product->set_sku( $car->vehicle_id );
    $product->set_virtual( true );
    $product->set_meta_data( array(
            'neg_miles' => $car->miles,
            'neg_year' => $car->year,
            'neg_trim' => $car->trim,
            'neg_drivetrain' => $car->drivetrain,
            'neg_fueltype' => $car->fuel_type,
            'neg_transmission' => $car->transmission,
            'neg_doors' => $car->doors,
            'neg_cylinders' => $car->cylinders,
            'neg_color_ext' => $car->color,
            'neg_color_int' => $car->interior_color,
            'neg_is_certified' => $car->is_certified,
            'neg_single_owner' => $car->carfax_1_owner,
            'neg_engine' => $car->engine,
            'neg_latitude' => $car->latitude,
            'neg_longitude' => $car->longitude
    ) );

    $product->save();
    $product_id = $product->get_id();

    if( !term_exists( $car->make, 'product_cat' ) ) {
        $make = wp_insert_term( $car->make, 'product_cat' ); 
        $model = wp_insert_term( $car->model, 'product_cat', array( 'parent' => $make['term_id'] ) );
    } else {
        $make = term_exists( $car->make, 'product_cat' );

        if( !term_exists( $car->model, 'product_cat' ) ) {
            $model = wp_insert_term( $car->model, 'product_cat', array( 'parent' => $make['term_id'] ) );
        } else {
            $model = term_exists( $car->model, 'product_cat' );
        }
        
    }
    wp_set_object_terms( $product_id, array( intval($make['term_id']), intval($model['term_id']) ), 'product_cat' );

    if( !empty( $car->body_type ) ) {
        if( !term_exists( $car->body_type, 'neg_body_style' ) ) {
            $body = wp_insert_term( $car->body_type, 'neg_body_style' ); 
        } else {
            $body = term_exists( $car->body_type, 'neg_body_style' );
        }
        
        wp_set_object_terms( $product_id, array( intval($body['term_id']) ), 'neg_body_style' );
    }


    $last_id = $car->ID;
} 

标签: phpwordpresswoocommerceplugins

解决方案


set_meta_data方法需要另一个元结构(带有id)。

我认为update_meta_data循环中更好的使用方法:

$product->update_meta_data('neg_miles', $car->miles);

推荐阅读