获取整个类别层次结构

时间:2016-01-06 20:02:12

标签: php wordpress woocommerce

我正在尝试为我的woocommerce网站设置一个分类列表。这很难描述,但我所拥有的与产品类别类似的东西......

Animals
 -Dog
  --Beagle
  --Poodle
 -Cat
 -Rabbit
Cars
 -Chevy
 -Toyota
People
Cities
Planets

如果我正在查看Poodle页面,我想将其显示为我的类别列表..

Animals
 -Dog
  --Beagle
  --Poodle

这是我目前的代码..

<?php
$args = array( 
    'taxonomy' => 'product_cat',
    'hide_empty' => false,
    'child_of' => get_queried_object()->term_id,
    //'child_of' => 6,
    'title_li' => __( 'Categories' ),
    'depth' => 3
);

wp_list_categories( $args ); 
?>

如果我为child_of设置了一个特定的术语ID(上面已注释掉),我就可以完成这项工作。但是我想让它自动运行。基本上我需要它循环回所有类别并从其最高级别类别开始列出术语。

它几乎就像显示面包屑一样,但在第一级别类别下显示所有儿童类别。

1 个答案:

答案 0 :(得分:0)

您应该从get_queried_object()获取的术语对象中感兴趣的两个属性,即

  • term_id这是术语

  • 的ID
  • parent这是术语“父”的整数值。如果该术语是最高级别,则此值为0,或者与当前术语的父级的术语ID相等的任何其他整数值

考虑到这一点,我们可以使用parent来确定正在查看的字词是层次结构中的顶级字词还是较低字词。这只能解决问题的一半,因为如果该术语是子项或孙项,我们仍然不知道parent何时不是0。为了确定这一点,我们将使用get_ancestors()来获取当前术语的所有层次结构,并从那里我们可以获得顶级术语

get_ancestors()返回一个术语ID数组,最后一个id是顶级术语,第一个id是传递术语的直接父项。对于顶级术语,将返回一个空数组。由于此处存在管理费用,我们将在运行get_ancestors()

之前首先检查当前术语是否为顶级术语

对于大块代码,我总是更容易编写一个正确的包装函数,我可以根据需要调用我的模板,所以让代码函数

/**
 * Function to display all terms from a given taxonomy in a hierarchy
 *
 * @param (array) $args Array of valid parameters for wp_list_categories
 */
function custom_term_list( $args = [] )
{
    // Make sure that this is a taxonomy term archive for the ttaxonomy 'product_cat', if not, return
    if ( !is_tax( 'product_cat' ) )
        return;

    // Get the current term object
    $term = get_queried_object();

    // Check if current term is top level or not
    if ( 0 == $term->parent ) {
        // Show all terms in hierarchy below the current term
        $parent = $term->term_id; 
        // If you need to show all terms regardless, you can do the following
        //$parent = 0;
    } else { // Term is not top level
        $hierarchy = get_ancestors( $term->term_id, $term->taxonomy );
        $parent    = end( $hierarchy );
    }

    // Make sure we override `child_of` if it is set by the user
    $args['child_of'] = $parent;
    // Make sure we set the taxonomy to the term object's taxonomy property
    $args['taxonomy'] = $term->taxonomy;

    wp_list_categories( $args );
}

在我们看一下如何使用这个功能之前,先注意几点:

  • 代码未经测试,可能有问题。请务必首先在本地进行测试,并将debug设置为true

  • 代码至少需要PHP 5.4

  • 我编写的代码只适用于分类法product_cat的分类法归档页面。您不需要将分类法传递给函数,而分类法则来自术语对象。但是,您可以修改代码以使用任何分类

  • 我编写代码的方式是,如果用户设置child_of参数,则不会使用该值。该函数将覆盖该值

让我们看看用例。您可以使用以下功能:( OP使用的代码

$args = [
    'hide_empty' => false,
    'title_li'   => __( 'Categories' ),
    'depth'      => 3
];
custom_term_list( $args );
相关问题