Question

<?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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top