10 August 2013
Category: WTG Blog
10 August 2013,
 0
wordpress-black-white-logo-sticker

Search WordPress Post Content

Search WordPress post content for a specific phrase or keyword. I looked for an existing WordPress function and there is nothing simple. There is WP_Query() but it is not light or simple and I would like to create a function that will come in useful in future. From what I could tell WP_Query() it does not search content on its own but includes title in its search also. So I came up with something very simple. Note: what I have below may only work with VARCHAR and I’ve giving two examples. The first is not recommended unless you can trust the needled/string.

Search WordPress Post Content


/**
* search wordpress post content for giving value
*
* uses MySQL LIKE - example: %your value%
*
* @package Video Blogger
* @since 1.0.0
*
* @return ID column using get_results()
*/
function wtgvb_search_post_content($needle,$post_type = 'post') {
 global $wpdb;
 return $wpdb->get_results(
 "
 SELECT ID
 FROM " . $wpdb->prefix . "posts
 WHERE post_content LIKE '%".$needle."%'
 AND post_type = '".$post_type."'
 "
 );
}

Apply Security

So we’re maybe just doing a SELECT query and searching WordPress post content. But the query above could be exploited. My use of the query could be exploited in the worst way so I must prepare it.

I’m using this function to build video playlists and the video themselves have their own post type. So the Video Blogger plugin searches that post type content for keywords in order to build the playlist. The search phrase may be used in a short-code and so we really must think about security. This example uses $wpdb->prepare() and we put two % around the $needle because the prepare function may strip one. I never seen evidence of this myself but the WordPress codex recommends it and it works just fine with them.


/**
*
* search wordpress post content for giving value
*
* uses MySQL LIKE - example: %your value%
*
* @package Video Blogger
* @since 1.0.0
*
* @return ID column using get_results()
*/
function wtgvb_search_post_content($needle,$post_type = 'post') {
 global $wpdb;

 $sql = $wpdb->prepare("SELECT ID
 FROM " . $wpdb->prefix . "posts
 WHERE post_content LIKE %s
 AND post_type = %s;",array('%%' . $needle . '%%',$post_type));

 return $wpdb->get_results($sql);
}

Leave a Reply