Make WordPress Core

Opened 10 years ago

Closed 10 years ago

#12898 closed feature request (worksforme)

Option in query_posts to include parent and/or grandparent categories

Reported by: vlasky Owned by: ryan
Milestone: Priority: normal
Severity: normal Version: 3.0
Component: Query Keywords: category, parent category
Focuses: Cc:


When specifying a category or categores to retrieve posts from, there should be a query_posts() option to include the parent and or grandparent categories.

This option could be called 'cat_levels', which would equal an integer number of levels to include.


query_posts('cat=2'); would just retrieve posts in category id 2

query_posts('cat=2&cat_levels=1') would retrieve posts in category id 2 and posts in its parent category (if it exists)

query_posts('cat=2&cat_levels=2') would retrieve all the above, plus the grandparent category (if it exists).

One application for this feature is for geotargeting content. Let's say that you use the visitor IP address to detect that the person is from Germany, you can then make 'Germany' a child category of a parent category 'European_Union'.

This means that not only can you display posts related to Germany, but posts concerning European Union issues that may be relevant to a German visitor.

Another request is an option to allow child categories to belong to multiple parents. This would be for the same reason. e.g. category 'Germany' could belong to two parent categories - 'European_Union' and 'German_Lanugage_Articles', which could then be searched to retrieve relevant posts via query_posts().

If anyone has any neat workaround for the above, I would also be interested to see them.

Change History (1)

#1 @scribu
10 years ago

  • Milestone 3.0 deleted
  • Resolution set to worksforme
  • Status changed from new to closed

Please post on the Ideas Forum before opening feture requests tickets.

Adding a 'level' argument to query_posts() is unnecessary. You just need to find the parent category and call query_posts() with that. Here's an example function:

function get_term_parent($term, $level = 1) {
	$taxonomy = $term->taxonomy;

	if ( !is_taxonomy_hierarchical($taxonomy) )
		return false;

	$parents = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));

	$term_id = $term->term_id;

	while ( $level-- ) {
		if ( $parents[$term_id] > 0 )
			$term_id = $parents[$term_id];

	return get_term($term_id, $taxonomy);

Example usage:

$cat_obj = get_term_by('slug', 'germany', 'category');
$grandpa = get_term_parent($cat_obj, 2);

query_posts(array('cat' => $grandpa->term_id));
Note: See TracTickets for help on using tickets.