Does mysql query works like this one, as $word value will search inside the tag of column post_title?
$word = test;
$pQuery = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts
WHERE post_content LIKE %s",'<h1>%'.$word.'%</h1>'), ARRAY_A)
CodePudding user response:
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.