apply_filters_ref_array( 'posts_search', string $search, WP_Query $query )

Filters the search SQL that is used in the WHERE clause of WP_Query.


Parameters

$search string
Search SQL for WHERE clause.
$query WP_Query
The current WP_Query object.

Top ↑

More Information

Since version 3.0.0, the posts_search filter is used to filter the search SQL that is used in the WHERE clause of WP_Query.


Top ↑

Source

File: wp-includes/class-wp-query.php. View all references

$search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );


Top ↑

Changelog

Changelog
Version Description
3.0.0 Introduced.

Top ↑

User Contributed Notes

  1. Skip to note 1 content
    Contributed by norrismp

    Example function search by title only:

    function wpdocs_search_by_title_only( $search, $wp_query ) {
        global $wpdb;
    
        if ( empty( $search ) ) {
            return $search; // skip processing - no search term in query
        }
    
        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';
        $search = '';
        $searchand = '';
    
        foreach ( (array) $q['search_terms'] as $term ) {
            $term = esc_sql( $wpdb->esc_like( $term ) );
            $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $searchand = ' AND ';
        }
    
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
            if ( ! is_user_logged_in() )
                $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    
        return $search;
    }
    add_filter( 'posts_search', 'wpdocs_search_by_title_only', 500, 2 );

You must log in before being able to contribute a note or feedback.