Support » Fixing WordPress » Sort by Custom Post & Date

  • I have site with 35k custom posts, how can I sort them by one custom field ASC and date DESC? Do I need to add a function in function.php or edit a wordpress file?

    Thank you for your help.

    F

Viewing 2 replies - 1 through 2 (of 2 total)
  • Add two functions to function.php:

    function home_modify_query( $query ) {
        if ( is_home() ) {
            $query->set( 'meta_key', 'zip_code' );
    	$query->set( 'orderby', 'meta_value' );
    	$query->set( 'order', 'ASC' );
        }
        return $query;
    }
    add_filter('pre_get_posts','home_modify_query');
    
    function sort_posts_orderby( $orderby ) {
    	if ( is_home() ) {
    	    $orderby = 'wp_postmeta.meta_value ASC, wp_posts.post_date DESC';
    	    return $orderby;
    	}
    }
    add_filter( 'posts_orderby', 'sort_posts_orderby' );
    Thread Starter wonderm

    (@wonderm)

    Thank you. The function doesn’t sort out the date. I have this function currenlty but it is slow:

    add_filter('pre_get_posts', 'sort_my_archive');
    function sort_my_archive($q) {
    if ($q->is_tax || $q->is_archive) {
        add_filter( 'posts_orderby', 'orderby_bad_car' );
    }
    return $q;
    }
    function orderby_bad_car( $order ) {
      $order = "(SELECT meta_value FROM wp_postmeta WHERE meta_key = 'wpcf-bad-car' AND post_id = wp_posts.ID) ASC, wp_posts.post_date desc";
      return $order;
    }

    [Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum’s parser.]

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sort by Custom Post & Date’ is closed to new replies.