I am trying to write a function for my functions.php file. I has to do the following;
- loop through search results and check the template
- if the template is ‘landing.php’ add it to ad array
- use the id’s collected in the array to exclude these pages from the search results.
I found some code on the WordPress Codex forum, I have added a little bit myself but unfortunately don’t know what i’m doing…
function filter_where($where = '') {
global $wpdb; // do I need this?
if ( is_search() ) {
if(is_page_template('landing.php')) { echo 'yes!'; } // ids collected here
$exclude = array(286);
for($x=0;$x<count($exclude);$x++){
$where .= " AND ID != ".$exclude[$x];
}
}
return $where;
}
add_filter('posts_where', 'filter_where');
The filter you are using
posts_where
affects the creation of SQL query, so by definition it is executed before query runs and you have any search results.So you cannot loop through results at this point, what you can do is retrieve or hardcode list of unwanted items from elsewhere and use them to modify query.
Update
Ok, this is faster to code than trying to solve with comments. This is probably not perfect but should be good starting point for what you want:
If you need to remove some specific pages or posts from your search results, you can easily do this using the “WP Hide Post” plugin.
According to its description: “Enables you to control the visibility of items on your blog by making posts/pages hidden on some parts of your blog, while still visible in other part.”
In particular, this plugin allows you to control the visibility of a post in various different views:
The posts will disappear from the places you choose them to disappear. Everywhere else they will show up as regular posts. In particular, permalinks of the posts still work, and if you generate a sitemap, with something like the Google XML Sitemaps the post will be there as well. This means that the content of your post will be indexed and searchable by search engines.
For a WordPress page, this plugin also allows you to control the visibility with two options: