1 回答

TA貢獻1862條經驗 獲得超6個贊
您無法真正在產品查詢中定位分組產品中的子產品,因為數據作為序列化數組存儲_children在表上的 meta_key下。wp_post_meta
但您可以做的是首先向分組產品中的所有子產品添加自定義字段。然后您將能夠使用該自定義字段來更改產品查詢。
以下函數將完成該工作,并且您只需運行它一次:
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
代碼位于活動子主題(或活動主題)的functions.php 文件中。
保存后,瀏覽您網站的任何頁面。然后刪除該代碼并保存。
現在,所有分組的兒童產品都將有一個自定義字段。如果您添加/創建更多分組產品,您將需要以下函數來將該自定義字段添加到子產品中:
// 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 );
? ? }
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。
現在完成,將隱藏所有產品的函數循環分組產品中的子產品:
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;
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。
- 1 回答
- 0 關注
- 143 瀏覽
添加回答
舉報