I'm trying to sort my posts like so:

- post title
- post title

- post title
- post title 

I have no problem achieving this with a custom query:

$args = array(
    'orderby' => 'name',
    'hide_emppty' => 1,
    'hierarchical' => false,
    'taxonomy' => 'course_category'
$categories = get_categories($args);
foreach ($categories as $category) : ?>

    <h3><?php echo $category->name; ?></h3>

    <?php $courses = new WP_Query( "post_type=courses&posts_per_page=-1&course_term=term-fall&course_category=" . $category->slug);  ?>
    <?php if ( $courses->have_posts() ) : while ( $courses->have_posts() ) : $courses->the_post(); ?>
        <?php the_title(); ?>
    <?php endwhile; endif; ?>

<?php endforeach; ?>

However, what I need to do is sort posts that come from a plugin-generated query (I have no (?) control over it) - so this needs to happen inside a normal if(have_posts()) : while (have_posts()) loop.

Is this even possible? The posts from this query are all of correct post type and course_term custom taxonomy, just need to get sorted by course_category taxonomy like above.

Thanks in advance for your help!

  • Did you tried using functions that get the terms instead of using get_categories? – whiteletters in blankpapers Jun 10 '13 at 11:21
  • I'm not sure you understand my question. The above code works, I just need to do something else with the same result, as explained later in the post. – Justine Jun 10 '13 at 12:42
  • This is sort of an issue of sorting default WP loop's posts by category vs. doing so with a custom query. How would I do it inside a default loop? – Justine Jun 10 '13 at 13:04
  • You can't really sort inside a Loop. You need to alter the query itself or sort the results from the query before the Loop starts. Without more information I don't know what the recommend. Try to add more detail. How does the plugin work? What does its output look like? – s_ha_dum Jun 10 '13 at 13:23

Got a quite radical solution :

function wpse_102497_modify_query_order( $query ) {
    if ( $query->is_main_query() ) {
      $query->set( 'orderby', 'title' );
add_action( 'pre_get_posts', 'wpse_102497_modify_query_order' );

Hope this will help.

  • I agree with this solution - use filters and hooks to alter the order - once you are in the loop, it's too late to re-order the post items, without a pretty comprehensive array_map – Eric Holmes Jun 10 '13 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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