Skip to content

Ability to get terms from PostQuery #3211

@cbirdsong

Description

@cbirdsong

I often want to creating a set of taxonomy filters to use alongside a query, but using get_terms() with the taxonomies attached to the post type returns all of the terms in the taxonomy even if none of the posts inside the query have that term attached.

My current workaround looks like this:

// Get some posts 
$posts = Timber::get_posts([ "post_type" => "projects", "category_name" => "featured", "posts_per_page" => "-1" ]);

// Make an array to hold the query's active taxonomies
$query_taxonomies = [];

// Loop through all the posts in the query
foreach ($posts as $post) {
	// Then loop through their terms
	foreach ($post->terms() as $term) {
		// Add a key to the array of taxonomies if it doesn't have one
		if (!array_key_exists($term->taxonomy, $query_taxonomies)) {
			$query_taxonomies[$term->taxonomy] = [];
		}

		// Add the term's ID to the corresponding taxonomy array if it isn't already included
		if (!in_array($term->id, $query_taxonomies[$term->taxonomy])) {
			$query_taxonomies[$term->taxonomy][] = $term->id;
		}
	}
}

// Loop through the query's active taxonomies, use the array of IDs to get an array of term objects, and add those to the Timber context
foreach ($query_taxonomies as $filter_key => $filter_term_ids) {
	if (!empty($filter_term_ids)) {
		$terms = Timber::get_terms([
			"taxonomy" => $filter_key,
			"include" => $filter_term_ids,
		]);
		$context["filters"][$filter_key] = $terms;
	}
}

I'm sure there is a more performant and resilient way to handle this, so it would be nice if Timber's PostQuery had a terms method that returns the terms from its posts.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions