Wildcard SQL Query – Narrowing Search Results

I am making a wildcard search query on the WordPress database for “Post Title”.

My results would vary:

Read More
  • “Post Title – 1”
  • “Post Title 2”
  • “Post Title #3”
  • “After the Post Title 1”
  • “Before the Post Title 1”
  • “After the Post Title 2”
  • “Before the Post Title 2”

I would like to limit my wildcard results to:

  • “Post Title – 1”
  • “Post Title 2”
  • “Post Title #3”

Any idea or algorithm I can achieve this?


Code

$query = "SELECT ID, `post_title` FROM `wp_posts` WHERE `post_title` LIKE '%".$titleRequest."%'";

$results = $wpdb->get_results($query);

Related posts

3 comments

  1. Modify the query like this:

    $query = "SELECT ID, `post_title` FROM `wp_posts` WHERE `post_title` LIKE '".$titleRequest."%'";
    
    $results = $wpdb->get_results($query);
    

    The initial % means “match anything here” – but you do not want to do that, you want to match only things that start with the title requested. The second % is ok – you do want to match things after Post Title, after all.

  2. Try this in the WHERE clause within your SQL Query:

    WHERE FieldName LIKE 'Post Title%';
    
  3. You will need to implement fuzzy logic in your search. But its a very complex algorithm, fortunately there are already some plugins that have implimented this algorithm like “Relevanssi“. Once installed it will override your current search mechanism and add its own, then you can modify it accordingly.

Comments are closed.