Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have an ajax request using wp_ajax sending one variable named "q" what I want to do is after the script get's the request to look inside the db and fetch the title and id of the corresponding posts that have either the title or the content "like" the variable so in other words here is my code :

global $wpdb;
$q = $_REQUEST['q'];
$sql = "SELECT * FROM wp_posts WHERE post_type = 'question' AND post_status = 'publish' 
            AND post_title LIKE %s OR post_content LIKE %s";
$posts = $wpdb->get_results($wpdb->prepare($sql,like_escape($q),like_escape($q)));

            echo '<ul>';
                foreach($posts as $post){
                    echo '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
                }
            echo '</ul>'; 

now I have the following posts : test test 2 Lorem lipsum ... Lorem lipsum ...

when I type "te" it should get all the posts because all of them contain "te" in their title but I get nothing

on typing "tes" it should get the tow "test" but again I get nothing and so one but if i type the full word "test" it gives me the tow "test" posts for the other one it does not work at all .

Can you please advise me on this ? It's getting annoying ...

/Edit/

I have made the following changes :

$posts = $wpdb->get_results($wpdb->prepare($sql,'%'.like_escape($q).'%','%'.like_escape($q).'%'));

now what happens is that i get all the posts from the db it seams like it ignores the post_type and post_status clauses

Regards, Paul.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

Dude, no need of the SQL mess! WP allows you to search through the post content or titles alphabetically using the search parameter.

So, use this solution instead...

global $wpdb;
$q = $_REQUEST['q'];
$posts = get_posts(array('s' => $q, 'post_type' => 'question', 'posts_per_page' => -1));

echo '<ul>';
foreach($posts as $post){
    echo '<li><a href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
}
echo '</ul>';

Put this in the AJAX handler function. It will work!

share|improve this answer
    
thank you your solution was the answer to my problem ! –  Paul Dumitru Jun 19 '12 at 12:37
    
You're welcome! Glad I could help! –  Rutwick Gangurde Jun 19 '12 at 12:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.