Zahid
Zahid

Reputation: 33

Display list of woo commerce categories by user defined order

I want to display all woo commerce categories by user defined order. As an example . I tried the following code:

            $args = array(
                'number' => $product_number,
                'order' => 'asc',

            );

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

This code works fine and returns an array or all category name in ascending order. What I want now is allow users to pass an array of category ids and display category list by the supplied id order. Is that possible ? Did some research but can not find any close solution.

Upvotes: 1

Views: 80

Answers (2)

Yamu
Yamu

Reputation: 1662

$product_number = 10; // Any number you have defined
$catsArray = array(1,2,3,4,5,8,10,20); // User provided array of terms ids
$product_categories= get_terms( array(
          'number'  => $product_number,
          'taxonomy' => 'product_cat',
          'include' => $catsArray,
          'hide_empty'  => false, 
          'orderby'  => 'include', 
          'order'    =>'ASC'
        ) );

Now you can get the categories in

Upvotes: 1

Elvin Haci
Elvin Haci

Reputation: 3572

You can do it with php loop. Which takes default ordered term array and build new, custom ordered array on it.

$user_arg = array(1,2,4,5);
$product_categories = get_terms('product_cat', $args);
$temporary_array=array();
foreach ($product_categorie as $pcat) {
$temporary_array[$pcat->term_id]=$pcat;
}
$final_array=array();
foreach($user_arg as $ua){
$final_array[$ua]=$temporary_array[$ua];
}

Now $final_array contains same data with $product_categories, but in custom order based on $user_arg.

Upvotes: 0

Related Questions