how to Sort post by custom taxonomy in wordpress?

Arpi Patel picture Arpi Patel · Nov 22, 2012 · Viewed 8.9k times · Source

I have created custom post in WordPress named "job_listing".

All posts are stored under "job_listing" and for the job we have information for the job type eg. permanent , part time etc.

This job_type is stored in the term and i want to search and sort all the jobs/posts by job_type.

Any one have the solution?

Answer

David Gard picture David Gard · Nov 22, 2012

Try something like this. It will first get all the non-empty terms for the job_type taxonomy, and then loop through them, outputting the associated posts.

I've made the assumption that you want it ordered alphabetically (both by job type and job listing), but you can change as required.

/** Get all terms from the 'job_type' Taxonomy */
$terms = get_terms('job_type', 'orderby=slug&hide_empty=1');    

/** Loop through each term one by one and output the posts that are assoiated to it */
if(!empty($terms)) : foreach($terms as $term) :

        /** Set the term name */
        $term_name = $term->slug;

        /** Set the query arguments and run the query*/
        $args = array(
            'job_type' => $term_name,
            'orderby' => 'title',
            'order' => ASC,
            'post_type' => 'job_listing',
            'posts_per_page' => -1
        );
        $term_posts = new WP_Query($args);

        /** Do something with all of the posts */
        if($term_posts->have_posts()) : while ($term_posts->have_posts()) : $term_posts->the_post();

                the_title();
                the_content();

            endwhile;
        endif;

        /** Reset the postdata, just because it's neat and tidy to do so, even if you don't need it again */
        wp_reset_postdata();

    endforeach;
endif;