星期三 , 22 1 月 2025

(精华)搜索自定义字段加标题和内容

function custom_search_query( $query ) {
    if ( !is_admin() && $query->is_search && $query->is_main_query() ) {
        // Clean up the search term
        $search_term = sanitize_text_field( $query->query_vars['s'] );

        // Add meta query to search in the custom fields
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key'     => 'partnumber',  // Custom field partnumber
                'value'   => $search_term,
                'compare' => 'LIKE'
            ),
            array(
                'key'     => 'oem_num',     // Custom field oem_num
                'value'   => $search_term,
                'compare' => 'LIKE'
            ),
        );

        // Set the meta query
        $query->set( 'meta_query', $meta_query );

        // Modify the search in title and content as well
        add_filter( 'posts_search', function( $search, $wp_query ) use ( $search_term, $wpdb ) {
            if ( empty( $search ) ) return $search;

            // Build the search query for custom fields and post title/content
            $search .= " OR EXISTS (
                SELECT * FROM $wpdb->postmeta
                WHERE $wpdb->postmeta.post_id = $wpdb->posts.ID
                AND $wpdb->postmeta.meta_key IN ('partnumber', 'oem_num')
                AND $wpdb->postmeta.meta_value LIKE '%$search_term%'
            )";

            return $search;
        }, 10, 2 );
    }
}
add_action( 'pre_get_posts', 'custom_search_query' );

上面的搜索结果是包含media file的, 也就是直接搜索图片的,如果不希望搜索图片的标题, 可以直接在函数里添加

// Exclude attachments (media files) $query->set( ‘post_type’, array( ‘post’, ‘page’, ‘product’ ) );