1 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
您無法真正在產(chǎn)品查詢中定位分組產(chǎn)品中的子產(chǎn)品,因?yàn)閿?shù)據(jù)作為序列化數(shù)組存儲(chǔ)_children在表上的 meta_key下。wp_post_meta
但您可以做的是首先向分組產(chǎn)品中的所有子產(chǎn)品添加自定義字段。然后您將能夠使用該自定義字段來更改產(chǎn)品查詢。
以下函數(shù)將完成該工作,并且您只需運(yùn)行它一次:
function add_a_custom_field_to_grouped_children_products() {
? ? // get all grouped products Ids
? ? $grouped_ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' =>'ids' ) );
? ? // Loop through grouped products
? ? foreach( $grouped_ids as $grouped_id ){
? ? ? ? // Get the children products ids
? ? ? ? $children_ids = (array) get_post_meta( $grouped_id, '_children', true );
? ? ? ? // Loop through children product Ids
? ? ? ? foreach( $children_ids as $child_id ) {
? ? ? ? ? ? // add a specific custom field to each child with the parent grouped product id
? ? ? ? ? ? update_post_meta( $child_id, '_child_of', $grouped_id );
? ? ? ? }
? ? }
}
add_a_custom_field_to_grouped_children_products(); // Run the function
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。
保存后,瀏覽您網(wǎng)站的任何頁面。然后刪除該代碼并保存。
現(xiàn)在,所有分組的兒童產(chǎn)品都將有一個(gè)自定義字段。如果您添加/創(chuàng)建更多分組產(chǎn)品,您將需要以下函數(shù)來將該自定義字段添加到子產(chǎn)品中:
// Add on the children products from a grouped product a custom field
add_action( 'woocommerce_process_product_meta_grouped', 'wc_action_process_children_product_meta' );
function wc_action_process_children_product_meta( $post_id ) {
? ? // Get the children products ids
? ? $children_ids = (array) get_post_meta( $post_id, '_children', true );
? ? // Loop through children product Ids
? ? foreach( $children_ids as $child_id ) {
? ? ? ? // add a specific custom field to each child with the parent grouped product id
? ? ? ? update_post_meta( $child_id, '_child_of', $post_id );
? ? }
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。經(jīng)過測(cè)試并有效。
現(xiàn)在完成,將隱藏所有產(chǎn)品的函數(shù)循環(huán)分組產(chǎn)品中的子產(chǎn)品:
add_filter( 'woocommerce_product_query_meta_query', 'hide_children_from_grouped_products' );
function hide_children_from_grouped_products( $meta_query ) {
? ? if( ! is_admin() ) {
? ? ? ? $meta_query[] = array(
? ? ? ? ? ? 'key'? ? ?=> '_child_of',
? ? ? ? ? ? 'compare' => 'NOT EXISTS'
? ? ? ? );
? ? }
? ? return $meta_query;
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。經(jīng)過測(cè)試并有效。
- 1 回答
- 0 關(guān)注
- 141 瀏覽
添加回答
舉報(bào)