post_search_columns
Allows you to change the list of columns searched when using the s search parameter in WP_Query.
By default, WordPress searches posts in three fields: post_title, post_excerpt, and post_content. This functionality was introduced through ticket #43867. Only these three fields are currently supported, although the list may be expanded in the future.
Usage
add_filter( 'post_search_columns', 'wp_kama_post_search_columns_filter', 10, 3 );
/**
* Function for `post_search_columns` filter-hook.
*
* @param string[] $search_columns Array of column names to be searched.
* @param string $search Text being searched.
* @param WP_Query $query The current WP_Query instance.
*
* @return string[]
*/
function wp_kama_post_search_columns_filter( $search_columns, $search, $query ){
// filter...
return $search_columns;
}
- $search_columns(string[])
- Array of column names to search.
- $search(string)
- Search string (query).
- $query(WP_Query)
- Current WP_Query instance.
Examples
#1 Exclude the post_excerpt field from search
Inside the hook callback, you can modify the list of search columns as needed and return the changed list. For example, you can exclude the post_excerpt column to speed up searches:
// Exclude the post_excerpt field from search.
add_filter( 'post_search_columns', 'wp_kama_post_search_columns_filter', 10, 3 );
/**
* Callback for the `post_search_columns` filter.
*
* @param string[] $search_columns Array of column names to search.
* @param string $search Search string.
* @param WP_Query $query Current WP_Query instance.
*
* @return string[] $search_columns Array of column names to search.
*/
function wp_kama_post_search_columns_filter( $search_columns, $search, $query ){
$search_columns = array_diff( $search_columns, [ 'post_excerpt' ] );
return $search_columns;
}
In this example, the callback removes post_excerpt from the list of search columns if it is present.
#2 Demo: values contained in the hook parameters
add_filter( 'post_search_columns', 'wp_kama_post_search_example', 10, 3 );
function wp_kama_post_search_example( $search_columns, $search, $query ){
print_r( $search_columns );
/*
Array (
[0] => post_title
[1] => post_excerpt
[2] => post_content
)
*/
var_dump( $search ); // string(15) "search for text"
print_r( $query ); // WP_Query Object
}
get_posts( [ 's'=>'search for text'] );Changelog
| Since 6.2.0 | Introduced. |
Where the hook is called
post_search_columns
wp-includes/class-wp-query.php 1483
$search_columns = (array) apply_filters( 'post_search_columns', $search_columns, $query_vars['s'], $this );