Created
November 16, 2023 13:41
-
-
Save everaldomatias/4ce56b64d324ab231b97130780f34888 to your computer and use it in GitHub Desktop.
Remove posts using term name on field filter of the block Query Loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function exclude_posts_by_filter_field( $query ) { | |
// Add other checks to determine exactly where you want to remove posts | |
if ( isset( $query->query['s'] ) && ! empty( $query->query['s'] ) ) { | |
// Continue if post_type equal `post` | |
if ( isset( $query->query['post_type'] ) && 'post' === $query->query['post_type'] ) { | |
$parts = explode( ' ', $query->query['s'] ); | |
$removals = []; | |
$filter = []; | |
foreach ( $parts as $part ) { | |
if ( strpos( $part, 'remove-' ) === 0 ) { | |
$removals[] = $part; | |
} else { | |
$filter[] = $part; | |
} | |
} | |
$filter_query = implode( ' ', $filter ); | |
$filter_query = preg_replace( '/\s+/', ' ', $filter_query ); | |
$query->query['s'] = $filter_query; | |
$query->set( 's', $filter_query ); | |
if( $removals ){ | |
// [..., 'post_tag', 'category'] | |
$taxonomies = ['editoria', 'destaque', 'post_tag', 'category']; | |
$tax_query = []; | |
foreach ( $taxonomies as $tax ) { | |
foreach( $removals as $removal ){ | |
$term = str_replace( 'remove-', '', $removal ); | |
$get_terms = get_term_by( 'slug', $term, $tax ); | |
if ( $get_terms && ! is_wp_error( $get_terms ) ) { | |
$get_term_id = $get_terms->term_id; | |
$tax_query[] = [ | |
'taxonomy' => $tax, | |
'terms' => [$get_term_id], | |
'operator' => 'NOT IN' | |
]; | |
} | |
} | |
} | |
if ( $tax_query ) { | |
$query->set( 'tax_query', $tax_query ); | |
} | |
} | |
} | |
} | |
} | |
add_action( 'pre_get_posts', 'exclude_posts_by_filter_field', 99 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment