<?php
ob_start();

define('IRK_PATH', trailingslashit(get_template_directory()));

add_action('pre_get_posts', 'irk_pre_get_posts');
function irk_pre_get_posts($query) {
    global $options;

    if (!$options->get_option('sku-search') || is_admin() || !$query->is_main_query() || !$query->is_search() || !get_query_var('post_type') == 'product') {
        return;
    }

    add_filter('posts_join', 'irk_search_join');
    add_filter('posts_where', 'irk_search_where');
    add_filter('posts_groupby', 'irk_search_groupby');
}

function irk_search_join($join) {
    global $wpdb;
    $join .= " LEFT JOIN $wpdb->postmeta __pm ON (" . $wpdb->posts . ".ID = __pm.post_id AND __pm.meta_key='_sku')";

    return $join;
}

function irk_search_where($where) {
    global $wpdb;
    $where = preg_replace(
        "/\(\s*{$wpdb->posts}.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
        "({$wpdb->posts}.post_title LIKE $1) OR ({$wpdb->posts}.post_content LIKE $1) OR (__pm.meta_value LIKE $1)",
        $where
    );

    return $where;
}

function irk_search_groupby($groupby) {
    global $wpdb;

    $my_groupby = "{$wpdb->posts}.ID";
    if (preg_match("/$my_groupby/", $groupby)) {
        return $groupby;
    }
    if (!strlen(trim($groupby))) {
        return $my_groupby;
    }
}

include_once(IRK_PATH . 'core.php');