![](/img/trans.png)
[英]Get current term name in Woocommerce product category archive pages
[英]Target WooCommerce product category archive pages from a child category term
我對產品類別有疑問。 我有一個這樣的類別:
-electronic
-- laptop
-- mobile
然后我想為electronic
下的所有產品創建一個邏輯,我使用is_product_category( 'electronic' )
,但它不適用於 electronic,只有當我使用mywebsite.com/product-category/electronic/mobile/
時 URL 是mywebsite.com/product-category/electronic
時它才有效mywebsite.com/product-category/electronic/mobile/
它不起作用。 我應該使用以下代碼還是有其他選擇:
is_product_category( ‘laptop’ )
is_product_category( ‘mobile’ )
您可以使用term_is_ancestor_of()
來檢查正在查看的當前術語(產品類別)是否屬於父術語。
我寫了一個簡單的助手 function:
/**
* @param int|object $parent ID or object term object to check.
* @return bool Whether the product category being viewed is a child of the given parent category.
*/
function wpse_is_child_product_category( $parent ) {
if ( ! is_product_category() ) {
return false;
}
return term_is_ancestor_of( $parent, get_queried_object(), 'product_category' );
}
用法:
if ( is_product_category( 5 ) || wpse_is_child_product_category( 5 ) ) {
// . . .
您可以創建一個自定義條件 function 來處理產品類別檔案中的任何子產品類別,例如(處理術語名稱、術語 slug 或術語 id) :
/**
* Determines whether the query is for an existing product category archive page or for an ancestors product category archive page.
*
* @param int|string term ID, term slug or term name to check.
* @return bool
*/
function is_maybe_child_product_category( $category ){
if( is_product_category( $category ) ) {
return true;
}
$object = get_queried_object();
if( ! is_a( $object, 'WP_Term') ) {
return false;
}
$taxonomy = $object->taxonomy;
$children = get_term_children( $object->term_id, $taxonomy );
$result = (array) term_exists( $category, $taxonomy );
if( ! empty( $result ) ) {
return false;
}
return in_array( reset($result), $children );
}
代碼進入活動子主題(或活動主題)的 functions.php 文件。 測試和工作。
用法:
if ( is_maybe_child_product_category( 'laptop' ) ) {
// Do something
}
我有一個關於產品類別的問題。 我有一個這樣的類別:
-electronic
-- laptop
-- mobile
然后我想為electronic
下的所有產品創建一個邏輯,我使用is_product_category( 'electronic' )
,但它不適用於電子,它僅在 URL 是mywebsite.com/product-category/electronic
時才有效,當我使用mywebsite.com/product-category/electronic/mobile/
它不起作用。 我應該使用以下代碼還是有其他選擇:
is_product_category( ‘laptop’ )
is_product_category( ‘mobile’ )
我仍在學習 php 並且我正在嘗試做一些接近你問題的事情。
這家商店出售圖片,每張圖片都按其藝術家分類。
CAT : ARTIST
SUB-CAT : ARTIST A
我需要存檔頁面上的每個產品都顯示其 SUB-CAT。
我不知道如何定位子類別,我被困在這一點上:
add_action( 'woocommerce_shop_loop_item_title','add_artist_name', 9);
function add_artist_name() {
global $product;
if (is_product_category( 'artistes' )){
echo // ADD SUBCATEGORY NAME
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.