Created
September 4, 2020 14:44
-
-
Save kodie/ea62aad8ae213109f933bc089879ff2f to your computer and use it in GitHub Desktop.
Get available term combinations for filtering in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Takes an array with a term taxonomy as the item keys and term ids as their values and | |
// returns the same array but with the values set as term ids that have posts associated | |
// with the term combination. (PHP7 and above only) | |
function get_term_filter_options($taxonomies, $query_args = array()) { | |
array_walk($taxonomies, function(&$value, $taxonomy) use($taxonomies, $query_args) { | |
$posts = null; | |
$others = array_filter($taxonomies, function($value, $key) use($taxonomy) { | |
return $key !== $taxonomy && !empty($value); | |
}, ARRAY_FILTER_USE_BOTH); | |
if (!empty($others)) { | |
$posts_args = array_merge_recursive($query_args, array( | |
'fields' => 'ids', | |
'numberposts' => -1, | |
'tax_query' => array( | |
'relation' => 'AND' | |
) | |
)); | |
foreach($others as $tax => $val) { | |
$posts_args['tax_query'][] = array( | |
'field' => 'term_id', | |
'taxonomy' => $tax, | |
'terms' => $val | |
); | |
} | |
$posts = get_posts($posts_args); | |
} | |
$value = get_terms(array( | |
'fields' => 'ids', | |
'taxonomy' => $taxonomy, | |
'object_ids' => $posts | |
)); | |
}); | |
return $taxonomies; | |
} | |
$filter_options = get_term_filter_options( | |
array( | |
'Services' => (int) get_query_var('services'), | |
'Market Sectors' => (int) get_query_var('market-sectors'), | |
'Construction Types' => (int) get_query_var('construction-types') | |
), | |
array('post_type' => 'projects') | |
); | |
// Returns: | |
// array( | |
// 'Services' => array(16, 19), | |
// 'Market Sectors' => array(9, 10), | |
// 'Construction Types' => array(3, 4, 6, 5, 7, 29) | |
// ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment