I want to change the query of search a custom post type in wordpress admin panel. I use this method:
function change_admin_search( $query ) {
$post_type = 'custom_post_type';
if( ! is_admin() )
return;
if ( $query->query['post_type'] != $post_type )
return;
$search_term = $query->query_vars['s'];
$persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$num = range(0, 9);
$persianNumbersOnly = str_replace( $num,$persian, $search_term);
$englishNumbersOnly = str_replace( $persian, $num, $search_term);
$query->query_vars['s'] = $englishNumbersOnly;
}
add_action( 'pre_get_posts', 'change_admin_search' );
In this query, it search only with $englishNumbersOnly
. I want to search with $englishNumbersOnly
OR $persianNumbersOnly
, and $query->query_vars['s']
have a OR
in query. Actually have a query like this :
post Like "%$englishNumbersOnly%" OR post Like "%$persianNumbersOnly%"
Thanks
CodePudding user response:
"I want to show all result ( persian and english )"
Search term argument of wp_query (i.e 's') accepts more than one keyword/term. The way you could feed it more than one keyword is to use
sign in the middle of the keywords, and it should be a string not an array. Like this:
$query->set( 's' => 'keywordOne keywordTwo keywordThree' )
We could use this to modify your query:
add_action('pre_get_posts', 'change_admin_search');
function change_admin_search($query)
{
$post_type = 'custom_post_type';
if (is_admin() && in_array($query->get('post_type'), array($post_type))) {
$search_term = sanitize_text_field($query->query_vars['s']);
$persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$num = range(0, 9);
$persianNumbersOnly = str_replace($num, $persian, $search_term);
$englishNumbersOnly = str_replace($persian, $num, $search_term);
$query->set('s', strval($englishNumbersOnly) . ' ' . strval($persianNumbersOnly));
}
}
Note:
- I've combined and modified your
if
statements. - I've changed your "post type" conditional check so that you could use more than one post type.
- I've used
sanitize_text_field
function on the searched keyword. - I've used
set
method for setting thes
value. - Using
strval
function is not necessary, but I've used it to make sure you don't get any error(s)/warning(s).
This has not been tested but, theoretically, it should work. Let me know if you could get it to work.
CodePudding user response:
I found the solution in WP_Query::parse_search method. As @Ruvee says, we can use ' '
sign to feed more than one search term for 's'
argument, But In parse_search method, the $searchand
value is ' AND '
and it ands search_terms. I Customize parse_search for custom_post_type
to use OR
instead of AND