Title: Sort by Custom Post &amp; Date
Last modified: August 21, 2016

---

# Sort by Custom Post & Date

 *  [wonderm](https://wordpress.org/support/users/wonderm/)
 * (@wonderm)
 * [12 years, 3 months ago](https://wordpress.org/support/topic/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)

 *  [Alicia](https://wordpress.org/support/users/amduffy/)
 * (@amduffy)
 * [12 years, 3 months ago](https://wordpress.org/support/topic/sort-by-custom-post-date/#post-4643835)
 * 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](https://wordpress.org/support/users/wonderm/)
 * (@wonderm)
 * [12 years, 3 months ago](https://wordpress.org/support/topic/sort-by-custom-post-date/#post-4643836)
 * 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.

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 2 replies
 * 2 participants
 * Last reply from: [wonderm](https://wordpress.org/support/users/wonderm/)
 * Last activity: [12 years, 3 months ago](https://wordpress.org/support/topic/sort-by-custom-post-date/#post-4643836)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
