Make WordPress Core

Opened 14 years ago

Closed 14 years ago

Last modified 14 years ago

#16088 closed defect (bug) (duplicate)

Excluding child category posts using pre_get_posts action hook not working

Reported by: jflagarde's profile jflagarde Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.1
Component: Query Keywords:
Focuses: Cc:

Description

Hello,

I have a similar problem to Ticket #15161. I'm not able to filter out the posts from a category using pre_get_posts.

I have a site which has the following structure:

  • parentcat1
    • subcat1
    • subcat2

On parentcat1 page, I would like to show only the parentcat1 posts, not its child posts from subcat1 and subcat2.

Initially, I had implemented some code in taxonomy-category.php like:

$args = array(
	'category__in' => array($parentcat_id)
);
$my_query = new WP_query();
$my_query->query($args);

while ($my_query->have_posts()) {
	$my_query->the_post();

I'm actually converting my theme to a parent/child theme structure with action and filter hooks. I tried the following code on WP3.0.3, WP3.0.4, on the Changesets: r16380 (suggested in Ticket #15161) and on the lastest svn build Changesets: r17206.

function jfl_exclude_child_posts($query) {
	if ( $query->is_category ) {
		$query->set('category__in', $parentcat_id);
	}
	return $query;
}
add_action('pre_get_posts', 'jfl_exclude_child_posts');

With the code above, the posts from the child categories are still present.

After hours of trial and error, I managed to find that temporary solution:

function jfl_exclude_child_posts2($query) {
	if ( $query->is_category ) {
		$query->set('category__in', $parentcat_id);
		$query->set('category__not_in', $subcat_ids) );
	}
	return $query;
}
add_action('pre_get_posts', 'jfl_exclude_child_posts2');

I would love to help to find the solution and modify the query.php file. I tried a few things, but I'm really not that experimented with programming. Any idea how to resolve this?

Change History (2)

#1 @SergeyBiryukov
14 years ago

  • Resolution set to duplicate
  • Status changed from new to closed

Looks similar to #16152, which has a patch. If it's a different issue, reopen.

#2 @ocean90
14 years ago

  • Milestone Awaiting Review deleted
Note: See TracTickets for help on using tickets.