| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side customizations for the `core/query` block. |
| 4 |
* |
| 5 |
* @package twentig |
| 6 |
*/ |
| 7 |
|
| 8 |
defined( 'ABSPATH' ) || exit; |
| 9 |
|
| 10 |
/** |
| 11 |
* Filter Query Loop block to handle current post filters. |
| 12 |
* |
| 13 |
* The `exclude-current` filter is deprecated in favor of the core `excludeCurrent` |
| 14 |
* query attribute (WP 7.1+); it is still handled here for content saved before the |
| 15 |
* editor migrated it. |
| 16 |
* |
| 17 |
* @param array $query The query arguments. |
| 18 |
* @param WP_Block $block Block instance. |
| 19 |
* @return array Modified query arguments. |
| 20 |
*/ |
| 21 |
function twentig_filter_query_block_current( $query, $block ) { |
| 22 |
if ( empty( $block->context['query']['twSinglePostsFilter'] ) || ! is_singular() ) { |
| 23 |
return $query; |
| 24 |
} |
| 25 |
|
| 26 |
$filter = $block->context['query']['twSinglePostsFilter']; |
| 27 |
$current_id = get_the_ID(); |
| 28 |
$post_type = get_post_type(); |
| 29 |
|
| 30 |
// Exclude current post for all filter types |
| 31 |
$query['post__not_in'] = isset( $query['post__not_in'] ) |
| 32 |
? array_merge( $query['post__not_in'], array( $current_id ) ) |
| 33 |
: array( $current_id ); |
| 34 |
|
| 35 |
if ( in_array( $filter, array( 'same-category', 'same-tag' ), true ) ) { |
| 36 |
$taxonomy = false; |
| 37 |
if ( 'post' === $post_type ) { |
| 38 |
$taxonomy = 'same-tag' === $filter ? 'post_tag' : 'category'; |
| 39 |
} elseif ( 'portfolio' === $post_type ) { |
| 40 |
$taxonomy = 'same-tag' === $filter ? 'portfolio_tag' : 'portfolio_category'; |
| 41 |
} |
| 42 |
|
| 43 |
if ( $taxonomy && taxonomy_exists( $taxonomy ) ) { |
| 44 |
$terms = get_the_terms( $current_id, $taxonomy ); |
| 45 |
if ( $terms && ! is_wp_error( $terms ) ) { |
| 46 |
$term_ids = wp_list_pluck( $terms, 'term_id' ); |
| 47 |
|
| 48 |
if ( ! empty( $term_ids ) ) { |
| 49 |
if ( ! isset( $query['tax_query'] ) ) { |
| 50 |
$query['tax_query'] = array(); |
| 51 |
} |
| 52 |
|
| 53 |
$query['tax_query'][] = array( |
| 54 |
'taxonomy' => $taxonomy, |
| 55 |
'terms' => $term_ids, |
| 56 |
); |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
return $query; |
| 63 |
} |
| 64 |
add_filter( 'query_loop_block_query_vars', 'twentig_filter_query_block_current', 10, 2 ); |
| 65 |
|