Skip to content

Instantly share code, notes, and snippets.

@VictorPietro
Created April 19, 2025 22:21
Show Gist options
  • Save VictorPietro/a268b5a6e4b9a3eedafb0bce3635da9f to your computer and use it in GitHub Desktop.
Save VictorPietro/a268b5a6e4b9a3eedafb0bce3635da9f to your computer and use it in GitHub Desktop.
Jet Smart Filters JSF Complex Query (meta field, taxonomy)
/**
* Filter for searching publications by post_title, meta field 'authors', and taxonomy 'conference' in JetSmartFilters.
* Uses the _search_publications query variable.
*/
add_filter( 'jet-smart-filters/query/final-query', function( $query ) {
global $wpdb;
// Loop through meta_query to check for _search_publications
foreach ( $query['meta_query'] as $index => $meta_query_item ) {
if ( isset( $meta_query_item['key'] ) && $meta_query_item['key'] === '_search_publications' ) {
// Get the search term from the value
$search_term = sanitize_text_field( $meta_query_item['value'] );
// Restrict the query to the 'publications' post type
$query['post_type'] = 'publications';
// Query the wp_posts table for post_title matches
$post_title_ids = $wpdb->get_col(
$wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE %s AND post_type = %s AND post_status = 'publish'",
'%' . $wpdb->esc_like( $search_term ) . '%',
'publications'
)
);
// Query the wp_postmeta table for meta_key 'authors' matches
$author_ids = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value LIKE %s",
'authors',
'%' . $wpdb->esc_like( $search_term ) . '%'
)
);
// Query the wp_terms and wp_term_relationships table for matching taxonomy 'conference'
$conference_ids = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT tr.object_id FROM {$wpdb->term_relationships} tr
INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
WHERE tt.taxonomy = %s AND t.name LIKE %s",
'conference',
'%' . $wpdb->esc_like( $search_term ) . '%'
)
);
// Combine the results from post_title, authors, and conference
$matching_ids = array_unique( array_merge( $post_title_ids, $author_ids, $conference_ids ) );
// If matching IDs are found, adjust the query to include those IDs
if ( ! empty( $matching_ids ) ) {
$query['post__in'] = ! empty( $query['post__in'] )
? array_intersect( $query['post__in'], $matching_ids ) // Narrow down existing IDs
: $matching_ids; // Start with matching IDs
} else {
// No matches found, prevent any results
$query['post__in'] = [ 0 ]; // Impossible condition
}
// Remove the original _search_publications meta_query to prevent conflicts
unset( $query['meta_query'][$index] );
// Stop processing further meta queries
break;
}
}
return $query;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment