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