Hi everyone,
I’m working on expanding the Search - Filter to another custom field (ACF) called card_transmutable. I use s as URL parameter, and my Query Loop is placed in an Archive Template.
So I got the filter to fire, but only on refresh. On AJAX search, or even if I use “submit”, it doesn’t filter as expected. Of course, the URL stays the same after the AJAX search and the refresh, but it looks like the refresh triggers native Wordpress search, not the bricks specific Query.
Here is the code I’m using, based on Adam Balee’s code (which includes all meta fields instead of just the one I need) :
<?php
/**
* Make every query that has ?s=… search title + the ACF field card_transmutable.
*/
add_action( 'init', function() {
// JOIN
add_filter( 'posts_join', function( $join ) {
global $wpdb;
if ( isset($_GET['s']) && $_GET['s'] !== '' ) {
$join .= ' LEFT JOIN ' . $wpdb->postmeta .
' ON ' . $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
} );
// WHERE
add_filter( 'posts_where', function( $where ) {
global $wpdb;
if ( isset($_GET['s']) && $_GET['s'] !== '' ) {
$where = preg_replace(
"/\(\s*{$wpdb->posts}\.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1)
OR ((".$wpdb->postmeta.".meta_key = 'card_transmutable')
AND ".$wpdb->postmeta.".meta_value LIKE $1)",
$where
);
}
return $where;
} );
// DISTINCT
add_filter( 'posts_distinct', function( $distinct ) {
if ( isset($_GET['s']) && $_GET['s'] !== '' ) {
return "DISTINCT";
}
return $distinct;
} );
});
Any idea on how to resolve this?