简体   繁体   English

仅使用get_terms获得类别名称

[英]get the category names only, with get_terms

<?php  
  $categories = array('bathroom', 'bar');  

    foreach ($categories as $category) {
        $args = array( 'post_type' => 'product', 'posts_per_page' => 3, 'product_cat' => $category, 'orderby' => 'rand' );
?>

I want to make the function above a little more dynamic. 我想使上面的功能更具动态性。 In such a way that I won't have to manually add the specific categories to the $categories variable. 这样,我就不必手动将特定类别添加到$ categories变量中。 Instead, I need something that will get only the names of the (woocommerce product) categories, and places them in an array. 相反,我需要只获取(woocommerce产品)类别名称的东西,并将它们放置在数组中。

I did get the list with this: 我确实得到了这个清单:

$category_list_items = get_terms( 'product_cat' );

foreach($category_list_items as $category_list_item){
    echo $category_list_item->name;
}

But I don't know how to get this list into the first function. 但是我不知道如何将此列表添加到第一个函数中。 Does anyone have an idea how to do this? 有谁知道如何做到这一点?

Thanks! 谢谢!

Based on my understanding of the question, you are populating $category_list_items as an array of category_list_item objects from your application. 根据我对问题的理解,您正在将$category_list_items填充$category_list_items应用程序中category_list_item对象的数组。 As a result you can turn your echo into an array of category names and then pass it to your function 结果,您可以将回声转换为类别名称数组,然后将其传递给函数

$categories = []; //array to store all of your category names
$category_list_items = get_terms( 'product_cat' );

foreach($category_list_items as $category_list_item){
    if(! empty($category_list_item->name) ){
        array_push($categories, $category_list_item->name);
    }
}

Once this foreach has been run, you will now have a categories array populated to pass to your above function. 一旦运行了此foreach,现在将填充一个categorys数组,以传递给上述函数。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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