<?php
/*
Plugin Name: Search Everything
Plugin URI: http://dancameron.org/searcheverything/
Description: This makes search queries look at pages, comments and posts instead of only posts. Based off of hacks and plugins from <a href="http://www.frorse.com/code/">Stinky Dad</a> and Rob Schluter's <a href="http://kwebble.com/blog_archives/2005/02/20/searching-pages-in-wordpress-15/">hack</a> and.
Author: Dan Cameron
Version: 0.01
Author URI: http://dancameron.org
*/ 


function add_comments_search_where($where) {
	global $wp_query;

	if (!empty($wp_query->query_vars['s'])) {
            $q = $wp_query->query_vars;	
		$q['s'] = addslashes_gpc($q['s']);
		$search = ' OR (';
		$q['s'] = preg_replace('/, +/', ' ', $q['s']);
		$q['s'] = str_replace(',', ' ', $q['s']);
		$q['s'] = str_replace('"', ' ', $q['s']);
		$q['s'] = trim($q['s']);
		if ($q['exact']) {
			$n = '';
		} else {
			$n = '%';
		}
		if (!$q['sentence']) {
			$s_array = explode(' ',$q['s']);
			$q['search_terms'] = $s_array;
			$search .= ' (comment_content LIKE \''.$n.$s_array[0].$n.'\')';
			for ( $i = 1; $i < count($s_array); $i = $i + 1) {
				$search .= ' AND (comment_content LIKE \''.$n.$s_array[$i].$n.'\')';
			}

			$search .= ' OR (comment_content LIKE \''.$n.$q['s'].$n.'\')';
			$search .= ') ';
		} else {
			$search = ' OR (comment_content LIKE \''.$n.$q['s'].$n.'\') ';
		}

		$where .= $search;
	}

	return $where;
}

function add_comments_search_join($join) {
	global $wp_query, $wpdb;

	if (!empty($wp_query->query_vars['s'])) {
		$join .= "LEFT JOIN $wpdb->comments ON ( comment_post_ID = ID  AND comment_approved =  '1') ";	
	}

	return $join;
}

add_filter('posts_where', 'add_comments_search_where');
add_filter('posts_join', 'add_comments_search_join');


function add_paged_search_where($where) {
	global $wp_query;
	if (!empty($wp_query->query_vars['s'])) {
		$where = str_replace(' AND (post_status = "publish"', ' AND ((post_status = "static" or post_status = "publish")', $where);
	}
	return $where;
}

add_filter('posts_where', 'add_paged_search_where');
?>
