How to modify the query in taxonomy-custom.php to sort term archives by a custom meta field?

I am trying to create theme pages for custom taxonomy terms in which the archives are ordered by a custom meta field.

I can do this with a new wp_query as follows:

Read More
        <?php $directory_archive_query = new WP_Query( 
            array( 
                'post_type' => 'directory',
                'posts_per_page' => 200,
                'meta_key' => 'surname',
                'orderby' => 'meta_value',
                'order' => 'ASC' ) ); ?>    

            <?php while($directory_archive_query->have_posts()) : $directory_archive_query->the_post(); ?>

However, I need this to work on the taxonomy-custom.php page so that each individual taxonomy term’s archive page is listed according to the custom meat field (called ‘surname’). If I use the wp_query, then of course that doesn’t work, because it no longer shows results for each specific term.

I have also tried to do this using pre_get_posts, but can’t make that work either. What I am expecting to happen is that all posts listed on the term archive page will be listed in ascending order by the surname meta key. That is not happening. Instead, they are just listing in the same order as if there were no pre_get_posts there. The code I have used is as follows:

<?php 

    function customize_customtaxonomy_archive_display ( $query ) {
        if (($query->is_main_query()) && (is_tax('services')))

        $query->set( 'post_type', 'directory' );                 
        $query->set( 'posts_per_page', '200' );
        $query->set( 'meta_key', 'surname' );           
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
    }

     add_action( 'pre_get_posts', 'customize_customtaxonomy_archive_display' );

?>

Really hoping that someone can help.

Thanks for your time.

Andrew.

Related posts

1 comment

  1. The pre_get_posts filter is immediately before the loop begins in
    taxonomy-services.php

    That is too late. The main query runs long before your template loads. Move your pre_get_posts filter to your theme’s functions.php, or a plugin or MU-Plugin file, and you should see the difference.

Comments are closed.