WooCommerce에서 프로그래밍 방식으로 가변 제품 및 두 가지 새로운 특성 생성
WordPress 플러그인에서 두 가지 새로운 Variante 속성을 가진 가변 제품("부모" 제품)을 프로그래밍 방식으로 만들고 싶습니다(따라서 API에 대한 HTTP 요청 없음).
이 두 가지 바리안트 속성도 즉시 생성해야 합니다.
이것이 어떻게 행해지는가?
(WooCommerce 버전 3)
업데이트 : wooCommerce 오브젝트를 사용하여 원하는 코드 행을 더 작성했고, WordPress 데이터베이스 오브젝트를 사용하여 용어, 용어, 포스트의 관계에 대한 누락된 데이터를 데이터베이스에 추가했습니다.그러나, 아무것도 그것을 작동시키기에 충분하지 않았습니다.또한 스택 오버플로우가 더 적합한 부분을 특정할 수 없었습니다. 그래서 더 좁은 문제를 제공할 수 없었습니다.
여기서는 새로운 제품 속성 + 값을 사용하여 새로운 변수 제품을 만드는 방법을 소개합니다.
/**
* Save a new product attribute from his name (slug).
*
* @since 3.0.0
* @param string $name | The product attribute name (slug).
* @param string $label | The product attribute label (name).
*/
function save_product_attribute_from_name( $name, $label='', $set=true ){
if( ! function_exists ('get_attribute_id_from_name') ) return;
global $wpdb;
$label = $label == '' ? ucfirst($name) : $label;
$attribute_id = get_attribute_id_from_name( $name );
if( empty($attribute_id) ){
$attribute_id = NULL;
} else {
$set = false;
}
$args = array(
'attribute_id' => $attribute_id,
'attribute_name' => $name,
'attribute_label' => $label,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0,
);
if( empty($attribute_id) ) {
$wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
set_transient( 'wc_attribute_taxonomies', false );
}
if( $set ){
$attributes = wc_get_attribute_taxonomies();
$args['attribute_id'] = get_attribute_id_from_name( $name );
$attributes[] = (object) $args;
//print_r($attributes);
set_transient( 'wc_attribute_taxonomies', $attributes );
} else {
return;
}
}
/**
* Get the product attribute ID from the name.
*
* @since 3.0.0
* @param string $name | The name (slug).
*/
function get_attribute_id_from_name( $name ){
global $wpdb;
$attribute_id = $wpdb->get_col("SELECT attribute_id
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return reset($attribute_id);
}
/**
* Create a new variable product (with new attributes if they are).
* (Needed functions:
*
* @since 3.0.0
* @param array $data | The data to insert in the product.
*/
function create_product_variation( $data ){
if( ! function_exists ('save_product_attribute_from_name') ) return;
$postname = sanitize_title( $data['title'] );
$author = empty( $data['author'] ) ? '1' : $data['author'];
$post_data = array(
'post_author' => $author,
'post_name' => $postname,
'post_title' => $data['title'],
'post_content' => $data['content'],
'post_excerpt' => $data['excerpt'],
'post_status' => 'publish',
'ping_status' => 'closed',
'post_type' => 'product',
'guid' => home_url( '/product/'.$postname.'/' ),
);
// Creating the product (post data)
$product_id = wp_insert_post( $post_data );
// Get an instance of the WC_Product_Variable object and save it
$product = new WC_Product_Variable( $product_id );
$product->save();
## ---------------------- Other optional data ---------------------- ##
## (see WC_Product and WC_Product_Variable setters methods)
// THE PRICES (No prices yet as we need to create product variations)
// IMAGES GALLERY
if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
$product->set_gallery_image_ids( $data['gallery_ids'] );
// SKU
if( ! empty( $data['sku'] ) )
$product->set_sku( $data['sku'] );
// STOCK (stock will be managed in variations)
$product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
$product->set_manage_stock(true);
$product->set_stock_status('');
// Tax class
if( empty( $data['tax_class'] ) )
$product->set_tax_class( $data['tax_class'] );
// WEIGHT
if( ! empty($data['weight']) )
$product->set_weight(''); // weight (reseting)
else
$product->set_weight($data['weight']);
$product->validate_props(); // Check validation
## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
$product_attributes = array();
foreach( $data['attributes'] as $key => $terms ){
$taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
$attr_label = ucfirst($key); // attribute label name
$attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
// NEW Attributes: Register and save them
if( ! taxonomy_exists( $taxonomy ) )
save_product_attribute_from_name( $attr_name, $attr_label );
$product_attributes[$taxonomy] = array (
'name' => $taxonomy,
'value' => '',
'position' => '',
'is_visible' => 0,
'is_variation' => 1,
'is_taxonomy' => 1
);
foreach( $terms as $value ){
$term_name = ucfirst($value);
$term_slug = sanitize_title($value);
// Check if the Term name exist and if not we create it.
if( ! term_exists( $value, $taxonomy ) )
wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
// Set attribute values
wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
}
}
update_post_meta( $product_id, '_product_attributes', $product_attributes );
$product->save(); // Save the data
}
코드가 기능합니다.php 파일에는 액티브한 아이 테마(또는 활성 테마).테스트 및 동작.
USAGE (2개의 새로운 Atribute + 값을 사용한 예) :
create_product_variation( array(
'author' => '', // optional
'title' => 'Woo special one',
'content' => '<p>This is the product content <br>A very nice product, soft and clear…<p>',
'excerpt' => 'The product short description…',
'regular_price' => '16', // product regular price
'sale_price' => '', // product sale price (optional)
'stock' => '10', // Set a minimal stock quantity
'image_id' => '', // optional
'gallery_ids' => array(), // optional
'sku' => '', // optional
'tax_class' => '', // optional
'weight' => '', // optional
// For NEW attributes/values use NAMES (not slugs)
'attributes' => array(
'Attribute 1' => array( 'Value 1', 'Value 2' ),
'Attribute 2' => array( 'Value 1', 'Value 2', 'Value 3' ),
),
) );
테스트 및 동작.
관련:
- Woocommerce에서 프로그래밍 방식으로 새 제품 특성 생성
- 새 속성 값을 사용하여 프로그래밍 방식으로 WooCommerce 제품 변형을 생성합니다.
- Woocommerce 3에서 CRUD 메서드를 사용하여 프로그래밍 방식으로 제품 생성
포스트메타에서 데이터를 설정/취득하기 위한 새로운 네이티브 기능을 사용하여 이 기능을 수행할 수도 있습니다.
다음으로 동작하는 예를 나타냅니다(Woocommerce 3의 디폴트 더미 제품에 근거).
//Create main product
$product = new WC_Product_Variable();
//Create the attribute object
$attribute = new WC_Product_Attribute();
//pa_size tax id
$attribute->set_id( 1 );
//pa_size slug
$attribute->set_name( 'pa_size' );
//Set terms slugs
$attribute->set_options( array(
'blue',
'grey'
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );
$product->set_attributes(array($attribute));
//Save main product to get its id
$id = $product->save();
$variation = new WC_Product_Variation();
$variation->set_regular_price(5);
$variation->set_parent_id($id);
//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
'pa_size' => 'blue'
));
//Save variation, returns variation id
$variation->save();
Woocommerce 3에서 사용할 수 있는 네이티브 기능을 사용하여 중량, 세금, sku 등을 추가할 수 있습니다.
함수로 포장하면 바로 사용할 수 있습니다.
Sarakinos의 답변은 작지만 중요한 두 가지 수정 사항만 적용되었다.
- 그
$attribute->set_id()
설정할 필요가 있다0
. - 그
$attribute->set_name();
그리고.$variation->set_attributes()
이 필요 없다pa_
프레픽스메서드는 이미 프레픽스를 처리하고 있습니다.
작업 코드는 다음과 같습니다.
//Create main product
$product = new WC_Product_Variable();
//Create the attribute object
$attribute = new WC_Product_Attribute();
//pa_size tax id
$attribute->set_id( 0 ); // -> SET to 0
//pa_size slug
$attribute->set_name( 'size' ); // -> removed 'pa_' prefix
//Set terms slugs
$attribute->set_options( array(
'blue',
'grey'
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
//If we are going to use attribute in order to generate variations
$attribute->set_variation( 1 );
$product->set_attributes(array($attribute));
//Save main product to get its id
$id = $product->save();
$variation = new WC_Product_Variation();
$variation->set_regular_price(10);
$variation->set_parent_id($id);
//Set attributes requires a key/value containing
// tax and term slug
$variation->set_attributes(array(
'size' => 'blue' // -> removed 'pa_' prefix
));
//Save variation, returns variation id
echo get_permalink ( $variation->save() );
// echo get_permalink( $id ); // -> returns a link to check the newly created product
제품은 맨살이며 '제품'으로 명명됩니다.이러한 값은 에서 설정할 필요가 있습니다.$product
하기 전$id = $product->save();
.
언급URL : https://stackoverflow.com/questions/47518333/create-programmatically-a-variable-product-and-two-new-attributes-in-woocommerce
'programing' 카테고리의 다른 글
'@babel/core' 모듈을 찾을 수 없습니다. (0) | 2023.02.27 |
---|---|
명령줄에서 sql plus까지 단일 명령어를 발행하려면 어떻게 해야 합니까? (0) | 2023.02.27 |
material-ui 앱바를 material-ui-next와 함께 사용하여 오른쪽 또는 왼쪽으로 이동하는 올바른 방법은 무엇입니까? (0) | 2023.02.27 |
Controller As 접근 방식을 사용하여 상속된 범위에 액세스 (0) | 2023.02.22 |
와의 JSON 파일 해석NET core 3.0/System.text.제이슨 (0) | 2023.02.22 |