繁体   English   中英

从子类别术语中定位 WooCommerce 产品类别存档页面

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM