从 WordPress 获取 WooCommerce 产品类别

我试图通过我的 WordPress 主题中的一个功能从 WooCommerce 获得产品类别

    function get_me_list_of($atts, $content = null)
{
$args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'product_cat' => $atts[0]);


$loop = new WP_Query( $args );


echo '<h1 class="upp">Style '.$atts[0].'</h1>';
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;


echo '<li><a href="'.get_permalink().'">'.get_the_post_thumbnail($loop->post->ID, 'thumbnail').'</a></li>';
echo '<li><a href="'.get_permalink().'">'.$loop->post->post_title.'</a></li>';


echo '<li><a href="">'.get_categories().'</a></li>';
endwhile;


echo "</ul>";


wp_reset_query();




}


?>

上面的代码返回一些产品,但是返回产品类别。

当我在上面的代码中包含 echo '<li><a href="">'.get_categories().'</a></li>';时,它会以数组的形式返回?

我如何改变这一点,以获得产品类别从伍德商务?

202299 次浏览
<?php


$taxonomy     = 'product_cat';
$orderby      = 'name';
$show_count   = 0;      // 1 for yes, 0 for no
$pad_counts   = 0;      // 1 for yes, 0 for no
$hierarchical = 1;      // 1 for yes, 0 for no
$title        = '';
$empty        = 0;


$args = array(
'taxonomy'     => $taxonomy,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';


$args2 = array(
'taxonomy'     => $taxonomy,
'child_of'     => 0,
'parent'       => $category_id,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo  $sub_category->name ;
}
}
}
}
?>

这将按层次结构列出所有顶级类别和它们下面的子类别。如果只想显示顶级类别,则不要使用内部查询。你喜欢怎么写就怎么写。

通过添加子类别的链接来改进 Suman.hasan95的答案。替换以下代码:

$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo  $sub_category->name ;
}


}

与:

$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
}
}

或者,如果您还希望为每个子类别设置一个计数器,则将其替换为:

$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
}
}

您还可以使用 wp _ list _ Category () ;

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

在我看来,这是最简单的解决办法

$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby'    => $orderby,
'order'      => $order,
'hide_empty' => $hide_empty,
);


$product_categories = get_terms( 'product_cat', $cat_args );


if( !empty($product_categories) ){
echo '


<ul>';
foreach ($product_categories as $key => $category) {
echo '


<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>




';
}
//Recursive function


function wc_loop_categories($parent = 0)
{


global $wpdb;


$query = "SELECT t.term_id AS ID, t.name AS title
FROM {$wpdb->prefix}terms AS t
LEFT JOIN {$wpdb->prefix}term_taxonomy AS ta
ON ta.term_id = t.term_id
WHERE ta.taxonomy='product_cat'
AND ta.parent=$parent
ORDER BY t.name ASC";


$cats = $wpdb->get_results($query);


foreach ($cats as $key => $cat) {
// get all sub_cats from current loop item
$cats[$key]->sub_cats = wc_loop_categories($cat->ID);
}


return $cats;
}

我已经准备好了递归创建菜单和添加到对象子元素的函数! Master Category oryId 是递归应该工作的类别 rootId。 仅供参考,我修改了 Suman.hasan95版本。

function getWpCat($masterCategoryId = 3360, $returnCategories)
{
    

$taxonomy     = 'product_cat';
$orderby      = 'name';
$show_count   = 1;      // 1 for yes, 0 for no
$pad_counts   = 1;      // 1 for yes, 0 for no
$hierarchical = 1;      // 1 for yes, 0 for no
$title        = '';
$empty        = 0;


$args = array(
'taxonomy'     => $taxonomy,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty,
'parent' => $masterCategoryId
);


$all_categories = get_categories($args);
    

foreach ($all_categories as $cat) {
$returnCategories[$cat->slug] = $cat;
$child = get_categories(array(
'taxonomy'     => $taxonomy,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty,
'parent' => $cat->cat_ID
));
if ( $child ) {
$returnCategories[$cat->slug]->child =  getWpCat($cat->cat_ID, $returnCategories[$cat->slug]->child);
}
        

}
return $returnCategories;
}


$returnCategories = [];
$categories = getWpCat(3360, $returnCategories);

为了更好地阅读,我建议使用一个类而不是函数,顺便说一下,用下面的代码你可以管理无限的子类:

    class WoocommerceCategoriesDropdown
{
const PRODUCT_CAT = 'product_cat';
const NAME = 'name';
const SHOW_COUNT = 0;
const PAD_COUNTS = 0;
const HIERARCHICAL = 1;
const TITLE = '';
const HIDE_EMPTY = 0;
const INITIAL_LEVEL = 0;
private $all_categories;
private $currentCategory;
private $level;
    

public function __construct($currentCategory)
{
$this->level = self::INITIAL_LEVEL;
$this->currentCategory = $currentCategory;
$this->all_categories = get_categories($this->getRootCategoryQueryArgs());
}
    

public function render()
{
echo '<select class="category-list-dropdown">';
foreach ($this->all_categories as $cat) {
$this->level = 0;
if ($cat->category_parent == 0) {
echo '<option ' . $this->getSelected($cat) . ' data-link="' . get_term_link($cat->slug, self::PRODUCT_CAT) . '">' . $cat->name . '</option>';
$this->renderSubCategories($cat);
}
}
echo '</select>';
}
    

/**
* @return array
*/
private function getRootCategoryQueryArgs(): array
{
return [
'taxonomy' => self::PRODUCT_CAT,
'orderby' => self::NAME,
'show_count' => self::SHOW_COUNT,
'pad_counts' => self::PAD_COUNTS,
'hierarchical' => self::HIERARCHICAL,
'title_li' => self::TITLE,
'hide_empty' => self::HIDE_EMPTY,
];
}
    

/**
* @return array
*/
private function getSubCategoryQueryArgs($categoryId): array
{
$args2 = $this->getRootCategoryQueryArgs();
$args2['child_of'] = $categoryId;
$args2['parent'] = $categoryId;
return $args2;
}
    

/**
* @param $cat
*/
public function renderSubCategories($cat): void
{
$subCats = get_categories($this->getSubCategoryQueryArgs($cat->term_id));
if (!empty($subCats)) {
$this->level++;
foreach ($subCats as $subCategory) {
echo '<option ' . $this->getSelected($subCategory) . ' data-link="' . get_term_link($subCategory->slug, self::PRODUCT_CAT) . '">' . $this->getCategoryLevelSpacer() . $subCategory->name . '</option>';
$this->renderSubCategories($subCategory);
}
}
}
    

/**
* @param $cat
* @return string
*/
private function getSelected($cat): string
{
$selected = get_term_link($cat->slug, self::PRODUCT_CAT) === get_term_link($this->currentCategory->slug, self::PRODUCT_CAT) ? ' selected="selected" ' : '';
return $selected;
}
    

private function getCategoryLevelSpacer(): string
{
$spacer = '';
for ($i = 0; $i < $this->level; $i++) {
$spacer .= "-";
}
if (!empty($spacer)) {
$spacer = $spacer . " ";
}
return $spacer;
}
}
enter code here

有效的解决方案获得所有类别和子类别,无论深度。

    /**
* Lists all product categories and sub-categories in a tree structure.
*
* @return array
*/
function list_product_categories() {
$categories = get_terms(
array(
'taxonomy'   => 'product_cat',
'orderby'    => 'name',
'hide_empty' => false,
)
);


$categories = treeify_terms($categories);


return $categories;
}


/**
* Converts a flat array of terms into a hierarchical tree structure.
*
* @param WP_Term[] $terms Terms to sort.
* @param integer   $root_id Id of the term which is considered the root of the tree.
*
* @return array Returns an array of term data. Note the term data is an array, rather than
* term object.
*/
function treeify_terms($terms, $root_id = 0) {
$tree = array();


foreach ($terms as $term) {
if ($term->parent === $root_id) {
array_push(
$tree,
array(
'name'     => $term->name,
'slug'     => $term->slug,
'id'       => $term->term_id,
'count'    => $term->count,
'children' => treeify_terms($terms, $term->term_id),
)
);
}
}


return $tree;
}

它也比当前的顶级答案高效得多,因为它只使用一个查询。

感谢 subZero 的初始代码... 我知道这是相当简单,但它可能只是帮助人们与快速复制粘贴!

这将返回一个漂亮的数组中的类别和 subs,用于构建菜单,而不是仅仅回显它。

function getCategories(){
$category = [];
$taxonomy     = 'product_cat';
$orderby      = 'name';
$show_count   = 0;      // 1 for yes, 0 for no
$pad_counts   = 0;      // 1 for yes, 0 for no
$hierarchical = 1;      // 1 for yes, 0 for no
$title        = '';
$empty        = 0;


$args = array(
'taxonomy'     => $taxonomy,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
//echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
$category[$category_id]['name'] = $cat->name;
$category[$category_id]['slug'] = get_term_link($cat->slug, 'product_cat');


$args2 = array(
'taxonomy'     => $taxonomy,
'child_of'     => 0,
'parent'       => $category_id,
'orderby'      => $orderby,
'show_count'   => $show_count,
'pad_counts'   => $pad_counts,
'hierarchical' => $hierarchical,
'title_li'     => $title,
'hide_empty'   => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
//echo $sub_category->name;
$sub_category_id = $sub_category->term_id;
$category[$category_id]['sub_category'][$sub_category_id]['name'] = $sub_category->name;
$category[$category_id]['sub_category'][$sub_category_id]['slug'] = get_term_link($sub_category->slug, 'product_cat');
}
}
}
}
return $category;
}