Make WordPress search only in post title

后端 未结 1 1253
情话喂你
情话喂你 2020-12-06 06:43

I have a new website and I want to modify WordPress Mystique theme 3.0 in order to search only in post title.

How can I do it?

相关标签:
1条回答
  • 2020-12-06 07:18

    There are numbers of articles available in Google if you have searched before you posted.
    WordPress search only in post title

    function __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', '__search_by_title_only', 500, 2);
    

    Add this code to your functions.php

    0 讨论(0)
提交回复
热议问题