Development

Views Taxonomy: Get Terms with Associated Nodes

This example serves as both an example of how to alter a Views2 query, as well as how to use the get_terms_by_count() function I’ve written.

Unfortunately there is not (at present) a Views2 taxonomy filter that lets you “Get only terms with at least X associated nodes.” We had a client request that terms without associated nodes be hidden. This was actually more complex than it sounds, but the solution led me to a whole new level of Views2 understanding. Views2 has a hook called hook_views_query_alter() that lets you alter a Views2 query before it is executed. This is exactly what we needed to do in order to only pull terms with associated nodes. Specifically, we needed to add an additional WHERE clause to the query.

So, we run a custom function to get all terms that have at least one associated node. We then loop through the resulting terms and build the where clause.

Unsure how to use this code, or where to put it?   Perhaps you need to look at Creating a Custom Module.

Resulting SQL query:

 

 

Leave a Reply

Your email address will not be published.