Erik Blomqvist
Erik Blomqvist

Reputation: 481

PHP: sort multi-dimensional array based on key for AJAX with WP_Query

I have a WP_Query that I'm using for a custom post type filter through AJAX. Every post type has a custom post taxonomy (category), but only one. In the filter process I want the result to be based on the names of the categories, THEN on the names of the products, but I haven't found the right documentation for using methods like usort or ksort with these types of arrays.

Here's my PHP:

$args = array(
    'posts_per_page'    => -1,
    'post_type'             => 'product',
    'orderby'                   => 'title',
    'order'                     => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy'  => 'products_tag',
            'field'         => 'slug',
            'terms'         => $taxonomy,
            'operator'  => 'AND',
        ),
    ),
);

$filter_query = new WP_Query($args);
$num_posts = $filter_query->found_posts;

if( $filter_query->have_posts() ):

    while( $filter_query->have_posts() ) : $filter_query->the_post();

        $titles[] = get_the_title();
        $ids[] = get_the_ID();
        $product_categories = get_the_terms( get_the_ID(), 'products_category' );
        $product_category = array_pop( $product_categories );
        $categories[] = $product_category->name;
        $permalinks[] = get_permalink();
        $image_field = get_field('images');
        $images[] = $image_field[0]['url'];
        $descriptions[] = get_field('short-description');

    endwhile;

endif;

wp_reset_postdata();

$response = array(
    'success' => true,
    'titles' => $titles,
    'ids' => $ids,
    'categories' => $categories,
    'permalinks' => $permalinks,
    'images' => $images,
    'descriptions' => $descriptions,
    'taxonomy' => $taxonomy,
    'num_posts' => $num_posts
);

So before the $results variable is declared, I want all the arrays to follow the $categories array in an easy way, but haven't a method how to. I might have misinterpreted the documentation completely, but I haven't seen my case appear in the php.net manuals.

Upvotes: 2

Views: 157

Answers (1)

Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

This should work, though I have not tried it.

$query = new WP_Query( array( 'post_type' => 'page', 'orderby' => 'title menu_order', 'order' => 'ASC' ) );

Notice how orderby has 2 parameters separated by a space.

Follow this thread for more info: How to order by two different things at once in a query in WordPress

Upvotes: 1

Related Questions