How do I access the array of posts from a custom taxonomy so I can sort it?

Viewed 71

I have a custom taxonomy called mwp_ss_supp. I have a page that displays all the posts using this code:

<?php $count = wp_count_posts('mwp_ss_supp')->publish;
    echo '<div id="post-count">' . $count . ' posts displayed</div>';?>
        
<?php       
if ( have_posts() ) : 
    while (have_posts()) : the_post(); 
    
    DO STUFF


  <?php 
    endwhile; 
endif; ?>

The problem is that all the posts are displaying in the order of latest post is the first on the list published. But I want to print them in a different order (ie, posts 1-10 are published first, posts 15-20 are published next, and 11-14 are published last, which ends up being published in alphabetical order by title). So how do I access this array of posts? There doesn't seem to be an array variable to play around with.

3 Answers

Show sql query for that. The sql query gets data from the database and determines the sort

You need to build a custom wordpress query WP_Query() to query posts against taxonomies:

<?php
$args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
    array(
      'taxonomy' => 'custom_taxonomy_type',
    );
  );
'orderby'=> 'title', 
'order' => 'ASC',
);

/**
* WP_Query()
* The WordPress Query class.
* @link https://developer.wordpress.org/reference/classes/wp_query/
*/
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
  while ( $query->have_posts() ) : $query->the_post();
    if( get_the_title() !== '' ):
      the_title( '<h1>', '</h1>' );
    endif;
    if( get_the_content() !== '' ):
      the_content();
    endif;
  endwhile;
endif;

/**
* wp_reset_postdata()
* After looping through a separate query, this function restores the $post global to the current post in the main query.
* @link https://developer.wordpress.org/reference/functions/wp_reset_postdata/
*/
wp_reset_postdata(); ?>

Learn more

Try adding a pre_get_posts() modifier to your theme's functions.php:

function taxo_posts($query)
{
    if ($query->is_tax('mwp_ss_supp') && $query->is_main_query())
    {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' ); // or DESC
    }
}
add_action('pre_get_posts', 'taxo_posts');
Related