Search code examples
phpwordpresssortingtaxonomy

sort posts based on meta key in a taxonomy archive page


I am using the below code to sort posts based on my meta key sub_seminars_0_start_date. The code works fine as it gets all the posts from portfolio post_type and then sorts them based on my meta key. However when I through a taxonomy query it displays nothing, a blank page with header and footer.

<?php 
                $args = array(
                'post_type'  => 'dt_portfolio',
                'post_status' => 'publish',
                'tax_query' => array(
            array(
            'taxonomy' => 'dt_portfolio_category',
            'field'    => 'slug',
            'terms'    => '',
        ),
    ),
                'meta_key'   => 'sub_seminars_0_start_date',
                'orderby'    => 'meta_value_num',
                'order'      => 'ASC',
            );

            $query = new WP_Query( $args ); ?>

How can I sort my posts that are in the taxonomy archive page ?

function change_order_for_events( $query ) {
    //only show future events and events in the last 24hours
    $yesterday = date('Ymd');

    if ( $query->is_main_query() && (is_tax('dt_portfolio_category') || is_post_type_archive('dt_portfolio')) ) {
        $query->set( 'meta_key', 'sub_seminars_0_start_date' );
        $query->set( 'orderby', 'meta_value_num' );
        $query->set( 'order', 'ASC' );

        //Get events after 24 hours ago
        $query->set( 'meta_value', $yesterday );
        $query->set( 'meta_compare', '>' );

       //Get events before now
       //$query->set( 'meta_value', current_time('timestamp') );
       //$query->set( 'meta_compare', '<' );
    }

}

add_action( 'pre_get_posts', 'change_order_for_events' );

this code in function.php will sort your posts based on a specific meta key value.

sub_seminars_0_start_date

I have created a custom taxonomy Seminar_Venues but the above code won’t work for that even after adjustin the parameters. Can you look


Solution

  • function pre_get_posts_hook($wp_query) {
    
        if( is_admin() ) {
    
            return $wp_query;
    
        }
    
        if ($wp_query->is_main_query() && ( is_category() || is_archive() ))
        {
            $wp_query->set( 'orderby', 'meta_value' );
            $wp_query->set( 'meta_key', 'sub_seminars_0_start_date' );
            $wp_query->set( 'order', 'ASC' );
            return $wp_query;
        }
    }
    
    add_filter('pre_get_posts', 'pre_get_posts_hook' );
    

    This worked for me to sort the posts based on a custom field mate key