As Title implies, Search the value inside the variable of $word inside the tag of column post_title content.
$word = test; $pQuery = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_content LIKE %s",'<h1>%'.$word.'%</h1>'), ARRAY_A)
ID post_title post_content 1 Hello <h1>This is a post</h1> <p>This is a description of a post to test if the query is working</p> <h1>Found me test</h1> 2 World <p>This is a description of a post to test if the query is working</p>
The query should view the data of of this ID
1 - Hello - <h1>This is a post</h1> <p>This is a description of a post to test if the query is working</p> <h1>Found me test</h1>
Advertisement
Answer
This probably won’t work.
You need to use $wpdb->esc_like() on the search-term text with
%
wildcards in it, or prepare will garble your query.$wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $wpdb->esc_like( '<h1>%'.$word.'%</h1>' ) );
You need to search for
'%<h1>%'.$word.'%</h1>%'
because your<h1>
tag isn’t at the beginning or the end of your post content. Put%
at the beginning and end of your search term.@tadman pointed out that your search won’t work if your
<h1>
tags contain attributes. There’s nothing you can do about that within the confines of SQL’s LIKE filter.If your post contains more than one
<h1>
tag your search term will consider words in the entire range between the first and last one.This will be very slow.
There’s an old slogan “If you solve a problem with a regular expression, now you have two problems”. Let’s modify that: “If you solve a problem with SQL’s LIKE, now you have two and a half problems”.
Point 4 could be a problem if your users are not tolerant of glitches.
You may want to consider a search plugin like Relevanssi for this kind of application.