dtxpz8785 2014-07-30 13:18
浏览 51
已采纳

使用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. Instead, I need something that will get only the names of the (woocommerce product) categories, and places them in an array.

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!

  • 写回答

1条回答 默认 最新

  • dongrui6787 2014-07-30 14:13
    关注

    Based on my understanding of the question, you are populating $category_list_items as an array of category_list_item objects from your application. 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.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?