Hi there,
I am trying to implement this live search script in a Wordpress project. It is working fine but I would like to add the ability to search a posts category as well. This requires me to reference the wp_terms (name and slug fields) as well as wp_posts. I am pretty green when it comes to this stuff - anyone able to shed some light?
Full Code as follows:
<?
require_once(dirname(__FILE__).'/wp-config.php');
$config['maxresult'] = 10; // Number of results to return
$config['maxbodylength'] = 210; // Trimming body length to x number of characters
if (isset($_REQUEST['s']) && trim($_REQUEST['s'] != ""))
{
$searchstring = addslashes($_REQUEST['s']);
if ($link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD))
{
if (mysql_select_db(DB_NAME, $link))
{
$storytable = $table_prefix . "posts";
$titlefield = "post_title";
$bodyfield = "post_content";
$status = "post_status";
$storyid = "guid";
$stmt = "SELECT $bodyfield, $titlefield, $storyid, MATCH($bodyfield, $titlefield) AGAINST ('$searchstring*' IN BOOLEAN MODE) AS score FROM $storytable WHERE ($status = 'publish' OR $status = 'static') AND MATCH($bodyfield, $titlefield) AGAINST ('$searchstring*' IN BOOLEAN MODE) ORDER BY score DESC LIMIT " . $config['maxresult'];
$searchstring = str_replace(" ", "% %", $searchstring);
$stmt2 = "SELECT $bodyfield, $titlefield, $storyid FROM $storytable WHERE ($status = 'publish' OR $status = 'static') AND ($titlefield LIKE '%$searchstring%' OR $bodyfield LIKE '%$searchstring%') LIMIT " . $config['maxresult'];
if ($result = mysql_query($stmt, $link))
{
if (mysql_num_rows($result) == 0)
{
$result = mysql_query($stmt2, $link);
}
if (mysql_num_rows($result) > 0)
{
echo "<ul>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// stripping images and links...
$contents = stripslashes(strip_tags($row[$bodyfield]));
if (strlen($contents) > $config['maxbodylength'])
$contents = substr($contents, 0, $config['maxbodylength']) . "...";
echo "<li><a href=\"$row[$storyid]\">" . $row[$titlefield] . "</a><p>$contents</p></li>";
}
echo "</ul>";
}
else
echo "<p class='error'>Sorry, no record matching your search criteria...</p>";
}
else
echo "<p class='error'>Sorry, search is not available.</p>";
}
else
echo "<p class='error'>Sorry, search is not available.</p>";
}
else
echo "<p class='error'>Sorry, search is not available.</p>";
}
?>