The second approach is basically similar to the discussed views approach, maybe slightly faster(or more faster if the view queries custom field from the database). Basically a view uses an underlying SQL query that is generated using WP_Query for post views, or WP_Term_Query for taxonomy views:
- https://developer.wordpress.org/reference/classes/wp_query/
- https://developer.wordpress.org/reference/classes/wp_term_query/
Whenever a view is rendered or used inside a loop, it will generate an SQL query. Assuming that you have n elements from the first taxonomy and m elements from the second taxonomy, you will end up with (2 + n * m) queries:
- 1 query to get the elements of the first taxonomy.
- 1 query to get the elements of the second taxonomy.
- n * m queries for each combination of terms.
Please note that this count is very optimistic and is true only if the solution is built entirely though the second approach. If implemented using views, additional queries will be run for each condition.
To optimize the second approach, you must implement some kind of caching. For example, at the bottom of the function, just before the "return $output;", you can save the $output variable on a transient. For example, set_transient( 'double_term_tree', $output, 12 * HOUR_IN_SECONDS ), to cache this menu for 12 hours.
https://developer.wordpress.org/apis/handbook/transients/
Then, you can create a custom shortcode that will check if the transient still exists on the database. If it exists it will return it. If it does not, it will return the "double_term_tree" function call.
// Inside shortcode body
if ( false === ( $output = get_transient( 'double_term_tree' ) ) ) {
return double_term_tree( 'product', 'brand', 'category' );
}
return $output
Transients have a timeframe. If you create/update/delete posts too often, you will need to purge the transient programmatically after a post is (un)assigned to a taxonomy term.
I hope this makes sense. However, this is not a simple custom code solution that we can help with. If you are not comfortable with programming, consider hiring a developer (see https://toolset.com/contractors/).