SHARE
TWEET

generate date archives for cpt

Beee Apr 7th, 2016 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3.     // Source: http://clubmate.fi/date-archives-for-wordpress-custom-post-types/
  4.  
  5.     // Custom post type specific rewrite rules
  6.     function events_rewrite_rules($wp_rewrite) {
  7.         // Here we're hardcoding the CPT in
  8.         $event_rules        = generate_date_archives_events('event', $wp_rewrite);
  9.         $wp_rewrite->rules  = $event_rules + $wp_rewrite->rules;
  10.         return $wp_rewrite;
  11.     }
  12.     // add_action('generate_rewrite_rules', 'events_rewrite_rules');
  13.  
  14.     // Generate date archive rewrite rules for a given custom post type
  15.     function generate_date_archives_events($cpt, $wp_rewrite) {
  16.         $event_rules    = array();
  17.         $post_type      = get_post_type_object($cpt);
  18.         $slug_archive   = $post_type->has_archive;
  19.         if ($slug_archive === false) {
  20.             return $event_rules;
  21.         }
  22.         if ($slug_archive === true) {
  23.             // Here's my edit to the original function, let's pick up
  24.             // custom slug from the post type object if user has
  25.             // specified one.
  26.             $slug_archive = $post_type->rewrite['slug'];
  27.         }
  28.  
  29.         $dates = array(
  30.             array(
  31.                 'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
  32.                 'vars' => array('year', 'monthnum', 'day')
  33.             ),
  34.             array(
  35.                 'rule' => "([0-9]{4})/([0-9]{1,2})",
  36.                 'vars' => array('year', 'monthnum')
  37.             ),
  38.             array(
  39.                 'rule' => "([0-9]{4})",
  40.                 'vars' => array('year')
  41.             )
  42.         );
  43.  
  44.         foreach ($dates as $data) {
  45.             $query = 'index.php?post_type='.$cpt;
  46.             $rule  = $slug_archive.'/'.$data['rule'];
  47.  
  48.             $i = 1;
  49.             foreach ($data['vars'] as $var) {
  50.                 $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
  51.                 $i++;
  52.             }
  53.  
  54.             $event_rules[$rule."/?$"] = $query;
  55.             $event_rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
  56.             $event_rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
  57.             $event_rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
  58.         }
  59.         return $event_rules;
  60.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top