<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

add_filter('posts_search', 'doosearchas_custom_search_filter', 10, 2);

/**
 * Customize the search SQL.
 */
function doosearchas_custom_search_filter($search, $query) {
    global $wpdb;
    if (!is_admin() && $query->get('s')) {
        $search_term = $query->get('s');
        $search_fields = $query->get('search_field');
        if (!$search_fields || $search_fields === 'all') {
            return $search;
        }
        $search_fields = explode(',', $search_fields);
        $search_term = esc_sql($wpdb->esc_like($search_term));
        $like = '%' . $search_term . '%';
        $search_parts = [];
        if (in_array('title', $search_fields)) {
            $search_parts[] = $wpdb->prepare("{$wpdb->posts}.post_title LIKE %s", $like);
        }
        if (in_array('excerpt', $search_fields)) {
            $search_parts[] = $wpdb->prepare("{$wpdb->posts}.post_excerpt LIKE %s", $like);
        }
        if (in_array('content', $search_fields)) {
            $search_parts[] = $wpdb->prepare("{$wpdb->posts}.post_content LIKE %s", $like);
        }
        if (!empty($search_parts)) {
            $search = " AND (" . implode(" OR ", $search_parts) . ")";
        }
    }
    return $search;
}
