Last active
          August 29, 2015 14:07 
        
      - 
      
 - 
        
Save jdhobbsuk/91039b2c2ef153d949ba to your computer and use it in GitHub Desktop.  
    Filter and order a custom post type by a meta_key, like events by past and future date
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // Set Events to date order (in admin), either future or past | |
| // ------------------------------------------------------------- | |
| function set_events_admin_order($wp_query) { | |
| if (is_admin()) : | |
| $post_type_req = 'events'; // change this | |
| $filter_by = 'event_date'; // change this | |
| $now = date('Ymd'); | |
| $post_type = $wp_query->query['post_type']; | |
| $status = $_GET['status']; | |
| if ( $post_type == $post_type_req) { | |
| $wp_query->set('meta_key', $filter_by); | |
| $wp_query->set('orderby', 'meta_value_num'); | |
| switch($status): | |
| case 'future'; | |
| $metaquery = array( | |
| array( | |
| 'key' => $filter_by, | |
| 'value' => $now, | |
| 'compare' => '>', | |
| ) | |
| ); | |
| $wp_query->set('order', 'ASC'); | |
| break; | |
| case 'past'; | |
| $metaquery = array( | |
| array( | |
| 'key' => $filter_by, | |
| 'value' => $now, | |
| 'compare' => '<', | |
| ) | |
| ); | |
| $wp_query->set('order', 'DESC'); | |
| break; | |
| endswitch; | |
| $wp_query->set( 'meta_query', $metaquery ); | |
| } | |
| endif; | |
| } | |
| add_filter('pre_get_posts', 'set_events_admin_order'); | |
| // Add submenus to Events | |
| //--------------------------- | |
| function events_add_submenu(){ | |
| add_submenu_page('edit.php?post_type=events','Future Events', 'Future', 'edit_post', 'edit.php?post_type='.$post_type_req.'&status=future'); | |
| add_submenu_page('edit.php?post_type=events','Past Events', 'Past', 'edit_post', 'edit.php?post_type='.$post_type_req.'&status=past'); | |
| } | |
| add_action('admin_menu', 'events_add_submenu', 10); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
When using a Custom Post Type to manage events / meetings, the listing page in the admin can quickly get bloated with past events. This code creates two new sub-menu items, where one only lists the future events, the other only listing the past events.