1

I am trying to do a search engine, I am using get_posts () function with parameter 's'. It finds me post by title and content but in a disorderly way, how could I tell it to first consult the titles and then put at the end the post whose content is what I am looking for?

   $query = array(
        'post_type' => 'tacos',
        'showposts' => 999,
        'posts_per_page' => 999,
    );

    $query['s'] = "Fish";

    $items = get_posts($query);
    $posts = array();

    foreach ($items as $position => $item) {...

This print the result of post with title and content that contains "Fish" but without order. I would like to put first title post and finally, the post with the content.

I finally solve it using specific sql query:

    global $wpdb;
    
    $query="SELECT 
    ID,
    post_title 
FROM $wpdb->posts
WHERE (`post_title`LIKE '%".$wpdb->esc_like($search)."%' OR `post_content`LIKE '%".$wpdb->esc_like($search)."%') AND `post_type`='page'
ORDER BY case
        when `post_title`LIKE '%".$wpdb->esc_like($search)."%' then 0
        when `post_content`LIKE '%".$wpdb->esc_like($search)."%' then 1
    END, post_title";

     $postid=$wpdb->get_results($query,'ARRAY_A');
1
  • I resolve it using custom sql query to wordpress database: – ciberelfo May 4 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.