tax query – Order WP_Query by The Order of an Array in Tax_Query


I have a wp_query that uses tax_query to which I pass an array of taxonomy term IDs. I’d like to order my results based on the order of that array but can’t get it to work and searching has got me nowhere. Example code below for reference. So this code actually orders the results by tax terms (dumb luck?) but the tax terms aren’t in the same order as $term_array. I’ve tried all the logical options for the ‘orderby’ parameter but nothing works that I’ve found.

I guess I could do a foreach on the $term_array but that seems like it would not be the most performant way to do it. Is there a better way?

Any ideas?

$term_array = array(3,5,1,4,2);

$args = array(
                'post_type'      => 'product',
                'post_status'    => 'publish',
                'posts_per_page' => -1,
                'orderby'        => 'menu_order',
                'order'          => 'ASC',
              'tax_query' => array(
                  'taxonomy' => 'product-brands',
                  'field' => 'term_id',
                  'terms' => $term_array,
                  'operator' => 'IN'
                  'taxonomy' => 'product_cat',
                  'field' => 'term_id',
                  'terms' => $main_product_cats
              'post__not_in' => $not_sold,

            $loop = new WP_Query( $args );
            if ( $loop->have_posts() ) { ... stuff ... }

Results are 1,2,3,4,5 and not the 3,5,1,4,2 order of $term_array

shagpun 9 months 2022-05-18T17:25:48-05:00 0 Answers 0 views 0

Leave an answer