Reputation: 540
I have found out a way to do this is in WordPress:
Say you post something under a sub-category called "news-sub", which parents category is "news". By deafult, the wordpress post will get posted under both news and news sub even if you only select it to be posted under the category news-sub. I've found a way for a post to only get posted in its sub category when you select it to be posted in just its sub category. Here is the code that inserts in functions.php:
add_action( 'pre_get_posts', 'my_post_queries' );
function my_post_queries( $query ) {
// not an admin page and is the main query
if (!is_admin() && $query->is_main_query()){
if(is_category()){
add_action('posts_where', 'current_category_only');
}
}
}
function current_category_only($where) {
$current_cat = get_query_var('cat');
if($current_cat){
global $wpdb;
return " AND ( $wpdb->term_relationships.term_taxonomy_id IN ($current_cat) )
AND $wpdb->posts.post_type = 'post' AND ($wpdb->posts.post_status = 'publish'
OR $wpdb->posts.post_status = 'private')";
}
return $where;
}
This code works awesome. But, it doesn't work with plugins. For example... I have a plugin that posts thumbnails and titles for your selected category. Say I select it to display only the "news" category.. if I posted something just under just the "news-sub" category, it still gets displayed via the plugin, regardless of my function code I mentioned earlier. I tried copy and pasting the function code into the plugin, but it didn't work. :(
So, how would I get this function to work with plugins that display categories? Would I modify it and leave it in the functions.php file, would I modify it and copy and paste it into my plugin file or how would I modify it at all? Any help would be tremendously appreciated! :)
Upvotes: 0
Views: 87
Reputation: 7830
The behavior you are describing is absolutely expected. Categories are hierarchical, so a parent category is expected to contain the subcategories and their posts.
Your posts_where
filter is trying to change the behavior to be more like tags. But some functions like get_posts()
do not run these filters:
Certain functions which retrieve posts do not run filters, so the posts_where filter functions you attach will not modify the query. To overcome this, set suppress_filters to false in the argument array passed to the function. The following code sample illustrates this.
$posts = get_posts( array( 'suppress_filters' => FALSE ) );
It depends on your plugin code if the filter is observed or not, so there is no clean way to rewrite the category logic. You might be better off using tags for the non-hierarchical semantics you seem to need. Or have a look at custom taxonomies which
are an extremely powerful way to group various items in all sorts of ways.
Upvotes: 1