Display Posts of a Category in Alphabetical Order (Custom Post Type)

  1. I have a custom post type called “link”
  2. I have a custom taxonomy for this post type called “link-category”
  3. I have a template file for this taxonomy, “taxonomy-link-category.php”
  4. I need the template to display the posts of the selected link category in alphabetical order

EDIT: On the LINKS page of the website all of the category names for the custom post type LINK are displayed in a list. Once a visitor clicks a category name I need wordpress to list all the posts in that category, in alphabetical order. I have it working, with the code below (using template file: taxonomy-link-category.php), but the posts are displayed chronologically, and only 10 of them (the wordpress default).

I’ve tried things like this: Displaying a custom post type alphabetically but of course it displays… EDIT: all of the LINK posts, not just the posts of the selected LINK category.

This is my current code in taxonomy-link-category.php, can I not just add 'orderby' => 'title', 'order' => 'ASC' somewhere/somehow?

<?php get_header(); ?>
  <div id="content">                    
    <h1>Links</h1>
    <h2><?php echo get_queried_object()->name; ?></h2>
    <?php if (have_posts()) :   // start the loop ?>                    
        <?php while (have_posts()) : the_post(); // loop the posts ?>
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?> 
        <?php endwhile;     // stop looping the posts ?>                                
        <?php else :        // what to do if there are no posts to show ?>
        <h3>No posts</h3>
    <?php endif;        // end the loop  ?>
  </div><!-- #content -->
<?php get_footer(); ?>

2 Answers
2

Use the pre_get_posts action to modify the query before it is run. Place this in your theme’s functions.php:

function wpd_tax_alpha( $query ) {
    if ( $query->is_tax('link-category') && $query->is_main_query() ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'wpd_tax_alpha' );

Leave a Comment