1

I have created new post type (hotels) and taxonomies (localisation).

I want to loop my hotels ordering by count DESC of taxonomies. I want to sort my hotel by count of localisation (I mean order from more hotels in localisation to less hotels).

I try this :

    $args = array(
        'post_type' => 'hotels',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'taxonomy_localisation',
                'field'    => 'term_id',
                'orderby'    => 'count',
                'order'    => 'DESC',
                'terms'    => $localisation_child->term_id,
            ),
        ),
    );

Is it possible using WP_query args ?

1 Answer 1

1

this topic might help you. By default args of WP_Query - this is impossible.

I don't think you can do that directly. Although you can save terms count for each post in a custom meta field (on post publish) and then in your query define sort by that meta field. Or while running your query, you can save terms count along with posts ids in another array, then sort them by count and print posts. Second one will consume more resources so I would recommend first method.

SELECT p.ID,COUNT(*) count FROM wp_term_relationships r, wp_posts p, wp_term_taxonomy x WHERE r.object_id = p.ID AND p.post_type = 'post' AND r.term_taxonomy_id = x.term_taxonomy_id AND x.taxonomy = 'post_tag' GROUP BY object_id ORDER BY count;

you can't do it directly, you need a filter and a CASE in the orderby eg

1
  • Yes I found this post, I guess it is the only way, thanks Commented Feb 12, 2018 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.