亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

隱藏 Woocommerce 循環中分組產品中的兒童產品

隱藏 Woocommerce 循環中分組產品中的兒童產品

PHP
婷婷同學_ 2023-08-26 09:53:49
讓分配給分組產品的所有單一產品在存檔/類別頁面上可用并可見并不是一個理想的解決方案,我想知道如何解決這個問題。我知道 WooCommerce 中有一個“可見性”選項,但這更不理想。據我了解,WooCommerce 現在用于meta data此用途,而不是post_parent用于此目的,因此,我請求幫助以了解如何更新此查詢以涵蓋該查詢。我嘗試過的這里的代碼不再起作用:add_action( 'woocommerce_product_query', 'hide_single_products_assigned_to_grouped_product_from_archive' );function hide_single_products_assigned_to_grouped_product_from_archive( $q ){    $q->set( 'post_parent', 0 );}
查看完整描述

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 文件中。經過測試并有效。

查看完整回答
反對 回復 2023-08-26
  • 1 回答
  • 0 關注
  • 143 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號