【问题标题】:List main product subcategories of a product category in WooCommerce列出 WooCommerce 中产品类别的主要产品子类别
【发布时间】:2020-12-02 14:51:33
【问题描述】:

我有一个名为“产品类型”的 WooCommerce 产品类别,我试图列出该类别下的所有类别,但不列出这些类别的子类别。例如,我有:

  • 产品类型
    • 硬质合金铣刀
    • 钓鱼工具
      • 儿童类别

我希望它列出“Carbide Mills”和“Fishing Tools”,而不是“Child Category”。

这是我的代码:

<ul>
<?php $terms = get_terms(
    array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
            'child_of' => 32,
            'post__not_in' => 25,
            'depth' => 1,
            'include_children' => false,
    )
);

// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
    // Run a loop and print them all
    foreach ( $terms as $term ) { ?>
        <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
            <li data-mh="234908ju243">
            <?php echo $term->name; ?>
            </li>
        </a><?php
    }
} ?>
</ul>

但它仍然返回“子类别”。我不确定为什么将深度限制为“1”并将“include_children”设置为“false”并不能解决问题。

【问题讨论】:

    标签: php wordpress woocommerce hierarchical-data taxonomy-terms


    【解决方案1】:

    您应该需要将参数 parent 与您的“产品类型”术语 ID 一起使用,以获得直接子术语 (子类别),如下所示:

    <ul>
    <?php 
    // Get the WP_Term object for "Product Types" product category (if needed)
    $parent_term = get_term_by('name', 'Product Types', 'product_cat' )->term_id;
    
    // Display "Product Types" category
    echo' <a href="' . esc_url( get_term_link( $parent_term ) ) . '">' . $parent_term->name . '</a><br>';
    
    // Get main direct subcategories
    $terms = get_terms( array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'parent'     => $parent_term->term_id,
    ) );
    
    // Check if any term exists
    if ( ! empty( $terms ) && is_array( $terms ) ) {
        // Loop through each term and print them all
        foreach ( $terms as $term ) {
            echo '<li data-mh="234908ju243">
            <a href="' . esc_url( get_term_link( $term ) ) . '">' . $term->name . '</a>
            </li>';
        }
    } ?>
    </ul>
    

    它应该可以工作。

    我对您的 html 结构进行了一些更改,因为 &lt;a&gt; 标记需要在 &lt;li&gt; 标记内。

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      相关资源
      最近更新 更多