問題描述
我的一個客戶要求根據(jù) Wordpress 的插件 Woocommerce 進行這種奇怪的更改,以便讓事情變得更容易"..
A client of mine requested this weird change based on Wordpress' plugin Woocommerce in order to make things "easier"..
是否有可能自動擁有所有產(chǎn)品屬性在創(chuàng)建產(chǎn)品時添加?
如果屬性中沒有輸入值,是否可以自動禁用在產(chǎn)品頁面上可見"復(fù)選框?
Also is it possible to have the "Visible on product page" checkbox automatically disabled if there is no value inputted in the attribute?
非常感謝任何幫助.
編輯(解釋):
這就是上面解釋的:
推薦答案
這是在創(chuàng)建新產(chǎn)品時自動添加所有現(xiàn)有產(chǎn)品變體 + 術(shù)語的方法.
Here is the way to auto add all existing product variations + terms when creating a new product.
代碼(評論):
add_action( 'save_post', 'auto_add_product_attributes', 50, 3 );
function auto_add_product_attributes( $post_id, $post, $update ) {
## --- Checking --- ##
if ( $post->post_type != 'product') return; // Only products
// Exit if it's an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Exit if it's an update
if( $update )
return $post_id;
// Exit if user is not allowed
if ( ! current_user_can( 'edit_product', $post_id ) )
return $post_id;
## --- The Settings for your product attributes --- ##
$visible = ''; // can be: '' or '1'
$variation = ''; // can be: '' or '1'
## --- The code --- ##
// Get all existing product attributes
global $wpdb;
$attributes = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}woocommerce_attribute_taxonomies" );
$position = 0; // Auto incremented position value starting at '0'
$data = array(); // initialising (empty array)
// Loop through each exiting product attribute
foreach( $attributes as $attribute ){
// Get the correct taxonomy for product attributes
$taxonomy = 'pa_'.$attribute->attribute_name;
$attribute_id = $attribute->attribute_id;
// Get all term Ids values for the current product attribute (array)
$term_ids = get_terms(array('taxonomy' => $taxonomy, 'fields' => 'ids'));
// Get an empty instance of the WC_Product_Attribute object
$product_attribute = new WC_Product_Attribute();
// Set the related data in the WC_Product_Attribute object
$product_attribute->set_id( $attribute_id );
$product_attribute->set_name( $taxonomy );
$product_attribute->set_options( $term_ids );
$product_attribute->set_position( $position );
$product_attribute->set_visible( $visible );
$product_attribute->set_variation( $variation );
// Add the product WC_Product_Attribute object in the data array
$data[$taxonomy] = $product_attribute;
$position++; // Incrementing position
}
// Get an instance of the WC_Product object
$product = wc_get_product( $post_id );
// Set the array of WC_Product_Attribute objects in the product
$product->set_attributes( $data );
$product->save(); // Save the product
}
代碼位于活動子主題(或活動主題)的 function.php 文件中.經(jīng)測試有效.
Code goes in function.php file of your active child theme (or active theme). tested and works.
這篇關(guān)于在 Woocommerce 中添加新產(chǎn)品時自動添加所有產(chǎn)品屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!