WooCommerce印刷子产品类别

时间:2015-05-25 作者:user2663914

我正在Woocommerce中使用Wordpress,我在产品内容产品单的详细页面上。php。

我创建了几个“sub”,只需打印与该产品关联的子类别。

我正在使用此代码:

$categories = array (
        \'type\' => \'product\',
        \'child_of\' => 1,
        \'parent\' => \'8\',
        \'orderby\' => \'term_group\',
        \'hide_empty\' => true,
        \'hierarchical\' = > 1,
        \'exclude\' => \'\',
        \'property\' => \'\',
        \'number\' => \'\',
        \'taxonomy\' => \'product_cat\',
        \'pad_counts\' => false);

$cats = get_categories ($categories);
foreach ($cats as $cat) {
    echo \'<a <br/> href="\'. get_term_link($cat-> slug,\' product_cat \').\' "> \'. $cat-> name.\'</a>\';
}
其中“parent”=>“8”是“我的类别父亲的id”

但此代码打印的所有子类别都不是空的,我只对这些子类别感兴趣,而不是本产品。

谢谢,祝你好运

2 个回复
SO网友:Omar Tariq

根据您的要求配置product\\u id和parent\\u category\\u id。

/* This is product id */
$product_id = 1;
/* This is the id of the parent category */
$parent_category_id = 8;

$cats = get_categories ( array (
    \'type\' => \'product\',
    \'parent\' => $parent_category_id,
    \'orderby\' => \'term_group\',
    \'hide_empty\' => true,
    \'hierarchical\' = > 1,
    \'exclude\' => \'\',
    \'property\' => \'\',
    \'number\' => \'\',
    \'taxonomy\' => \'product_cat\',
    \'pad_counts\' => false
));

$non_empty_sub_categories_ids = array_map(create_function(\'$cat\', \'return $cat->term_id;\'), $cats);

$product_cats = get_the_terms( $product_id, \'product_cat\' );
foreach ($product_cats as $product_cat) {
    if(in_array($product_cat->term_id, $non_empty_sub_categories_ids)) {
        echo \'<a <br/> href="\'. get_term_link($product_cat->slug,\' product_cat \').\' "> \'. $product_cat->name.\'</a>\';        
    }
}

SO网友:Mamun Ahmed
<?php 

$args = array(
    \'taxonomy\' => \'product_cat\',
    \'slug\' => array(\'category_slug\'),
    \'hide_empty\' => true
);
$product_cat = get_terms( $args );
foreach ($product_cat as $parent_product_cat){
echo \'<ul> 
        <li><a href="\'.get_term_link($parent_product_cat->term_id).\'">\'.$parent_product_cat->name.\'</a>
            <ul> \';
                $child_args = array(
                    \'taxonomy\' => \'product_cat\',
                    \'hide_empty\' => true,
                    \'parent\'   => $parent_product_cat->term_id
                );
                $child_product_cats = get_terms( $child_args );
                foreach ($child_product_cats as $child_product_cat) {
                    echo \'<li><a href="\'.get_term_link($child_product_cat->term_id).\'">\'.$child_product_cat->name.\'</a></li>\';
                }
    echo \'  </ul>
        </li>
    </ul>\';
}

?>

结束

相关推荐