Skip to content

Instantly share code, notes, and snippets.

@ihslimn
Last active December 29, 2023 13:47
Show Gist options
  • Save ihslimn/6f877e25227c26cc262e1f55a038a7ea to your computer and use it in GitHub Desktop.
Save ihslimn/6f877e25227c26cc262e1f55a038a7ea to your computer and use it in GitHub Desktop.
JetSmartFilters Search for the exact value in the list
<?php
class JSF_Search_In_List {
private $prefix = 'in_list';
private $delimiter = '__';
public function __construct() {
add_filter( 'jet-smart-filters/query/final-query', array( $this, 'modify_query' ) );
add_action( 'jet-smart-filters/admin/register-dynamic-query', array( $this, 'helper_dynamic_query' ) );
}
public function modify_query( $query ) {
if ( empty( $query['meta_query'] ) ) {
return $query;
}
foreach ( $query['meta_query'] as $i => $clause ) {
if ( ! is_array( $clause ) || false === strpos( $clause['key'] ?? '', $this->prefix . $this->delimiter ) ) {
continue;
}
$clause['key'] = str_replace( $this->prefix . $this->delimiter, '', $clause['key'] );
$clause['value'] = sprintf( '\b%s\b', preg_quote( $clause['value'] ) );
$clause['compare'] = 'REGEXP';
$query['meta_query'][ $i ] = $clause;
}
return $query;
}
public function helper_dynamic_query( $dynamic_query_manager ) {
$dynamic_query_item = new class( $this->prefix, $this->delimiter, 'Jet Smart Filters - Search In List' ) {
public function __construct( $key, $delimiter, $label ) {
$this->key = $key;
$this->delimiter = $delimiter;
$this->label = $label;
}
public function get_name() {
return $this->key;
}
public function get_label() {
return $this->label;
}
public function get_extra_args() {
return array(
'exact_field' => array(
'type' => 'text',
'title' => 'Meta key',
),
);
}
public function get_delimiter() {
return $this->delimiter;
}
};
$dynamic_query_manager->register_item( $dynamic_query_item );
}
}
new JSF_Search_In_List();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment