Advertisement
mbis

Custom post type + taxonomy archive

Mar 9th, 2020
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.10 KB | None | 0 0
  1. function pm_detect_archives($request) {
  2.     global $wp, $wpdb;
  3.  
  4.     $post_types = array(
  5.         'events' => 'events'
  6.     );
  7.  
  8.     $taxonomies = array(
  9.         'solutions'
  10.     );
  11.  
  12.     // Parse the URI (name_of_post_type/taxonomy_term)
  13.     preg_match('/([^\/]+)\/([^\/]+)(?:\/page\/([\d]+))?/', $wp->request, $parts);
  14.  
  15.     if(!empty($parts[1]) && !empty($post_types[$parts[1]])) {
  16.         // Get post type
  17.         $post_type = $post_types[$parts[1]];
  18.  
  19.         // Get term
  20.         $term = $wpdb->get_row($wpdb->prepare("
  21.             SELECT * FROM {$wpdb->terms}
  22.             LEFT JOIN {$wpdb->term_taxonomy} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
  23.             WHERE slug = %s",
  24.             sanitize_title($parts[2])
  25.         ));
  26.  
  27.         // Filter the query if both post type & term were found
  28.         if(!empty($term) && in_array($term->taxonomy, $taxonomies)) {
  29.             $request = array(
  30.                 'post_type' => $post_type,
  31.                 'taxonomy' => $term->taxonomy,
  32.                 'term' => $term->slug,
  33.                 'do_not_redirect' => 1,
  34.             );
  35.  
  36.             // Suport pagination
  37.             if(!empty($parts[2])) {
  38.                 $request['paged'] = $parts[2];
  39.             }
  40.         }
  41.     }
  42.  
  43.     return $request;
  44. }
  45. add_filter('request', 'pm_detect_archives', 99);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement