I'm trying to create a search bar that will show me titles of posts when the user types into the text field.
I'm completely new to this and I really don't know how to go about doing this. What would I do?
Here is the text input html element:
<input type='text' id='searchField' class='pushLeft tabRight hide' onKeyUp="autoSearch('<?php echo esc_js(site_url()); ?>')"/>
And here is the javascript, which I'd like to point out is in a folder called "js" and in that is my javascript file "general.js:"
function autoSearch(link)
{
$("#searchResults").width($("#searchArea").width());
if($("#searchField").val() != "")
{
$.post(link,{autoSearch:"", value:$("#searchField").val()},function(data){
$("#searchResults").show();
$("#searchResults").html(data.everything);
},"json");
}
else
{
$("#searchResults").hide();
}
}
Then in functions.php I have the following section of code:
isset( $_POST['autoSearch'] ) && add_action( 'after_setup_theme', 'wpse_60353_autosearch' );
function wpse_60353_autosearch()
{
global $wpdb;
$searchQuery = mysql_escape_string($_POST['value']);
$mypostids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_title LIKE '$searchQuery' LIMIT 5");
$args = array('post__in='.$mypostids);
$res = new WP_Query($arg);
$titles ="";
while ( $res->have_posts() ) : $res->the_post();
$titles .= get_the_title().'<br />';
endwhile;
echo json_encode(array("everything"=>"hello"));
wp_reset_postdata();
exit; // All done, stop WP continuing
}
I get a POST response saying this:
301 Moved Permanently
prepare()andlike_escape()in queries. --- Then there're the questions where, how and when you use the code you showed above. Could be that you're too early and$wpdb;isn't yet initialized. – kaiser Jul 31 '12 at 18:46