WP_Query_Integration.php
101 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Pods\Theme; |
| 4 | |
| 5 | use Exception; |
| 6 | use WP_Query; |
| 7 | |
| 8 | /** |
| 9 | * WP_Query specific functionality. |
| 10 | * |
| 11 | * @since 2.8.0 |
| 12 | */ |
| 13 | class WP_Query_Integration { |
| 14 | |
| 15 | /** |
| 16 | * Add the class hooks. |
| 17 | * |
| 18 | * @since 2.8.0 |
| 19 | */ |
| 20 | public function hook() { |
| 21 | add_action( 'pre_get_posts', [ $this, 'show_cpt_on_core_taxonomy_archive' ] ); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Remove the class hooks. |
| 26 | * |
| 27 | * @since 2.8.0 |
| 28 | */ |
| 29 | public function unhook() { |
| 30 | remove_action( 'pre_get_posts', [ $this, 'show_cpt_on_core_taxonomy_archive' ] ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Show Custom Post Type on core Taxonomy archive. |
| 35 | * |
| 36 | * @since 2.8.0 |
| 37 | * |
| 38 | * @param WP_Query $query The WP_Query instance. |
| 39 | */ |
| 40 | public function show_cpt_on_core_taxonomy_archive( $query ) { |
| 41 | // Skip on admin screens. |
| 42 | if ( is_admin() ) { |
| 43 | return; |
| 44 | } |
| 45 | |
| 46 | // Skip if not on the archive we want. |
| 47 | if ( |
| 48 | ! empty( $query->query_vars['suppress_filters'] ) |
| 49 | || ! $query->is_main_query() |
| 50 | || $query->is_404() |
| 51 | || ( |
| 52 | ! $query->is_category() |
| 53 | && ! $query->is_tag() |
| 54 | ) |
| 55 | ) { |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | $object = $query->get_queried_object(); |
| 60 | |
| 61 | if ( ! isset( $object->taxonomy ) ) { |
| 62 | return; |
| 63 | } |
| 64 | |
| 65 | $taxonomy = $object->taxonomy; |
| 66 | |
| 67 | // Find all CPT that have this taxonomy set. |
| 68 | $api = pods_api(); |
| 69 | |
| 70 | try { |
| 71 | $post_types_to_show = $api->load_pods( [ |
| 72 | 'args' => [ |
| 73 | 'archive_show_in_taxonomies_' . $taxonomy => 1, |
| 74 | ], |
| 75 | 'names' => true, |
| 76 | ] ); |
| 77 | } catch ( Exception $exception ) { |
| 78 | pods_debug_log( $exception ); |
| 79 | |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | $post_types_to_show = array_keys( $post_types_to_show ); |
| 84 | |
| 85 | $existing_post_types = $query->get( 'post_type' ); |
| 86 | |
| 87 | if ( empty( $existing_post_types ) ) { |
| 88 | $existing_post_types = [ |
| 89 | 'post', |
| 90 | ]; |
| 91 | } elseif ( ! is_array( $existing_post_types ) ) { |
| 92 | $existing_post_types = (array) $existing_post_types; |
| 93 | } |
| 94 | |
| 95 | $post_types_to_show = array_unique( array_merge( $existing_post_types, $post_types_to_show ) ); |
| 96 | |
| 97 | $query->set( 'post_type', $post_types_to_show ); |
| 98 | } |
| 99 | |
| 100 | } |
| 101 |