-
-
Save wpmark/9da1176af487d744d2c7 to your computer and use it in GitHub Desktop.
Get Posts in Terms Array
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 | |
function wpmark_get_posts_in_terms_array( $args = array() ) { | |
/* set some defaults */ | |
$defaults = array( | |
'orderby' => 'id', | |
'taxonomy' => '', | |
'posts' => '', | |
); | |
/* merge defaults with passed args */ | |
$args = wp_parse_args( $args, $defaults ); | |
/* setup our default output array */ | |
$output = array(); | |
/* get the terms for person type */ | |
$types = get_terms( | |
$args[ 'taxonomy' ], | |
array( | |
'orderby' => $args[ 'orderby' ], | |
'fields' => 'names' | |
) | |
); | |
/* loop through each term */ | |
foreach( $types as $type ) { | |
/* add this term id as an array key */ | |
$output[ $type ] = array(); | |
} | |
/* loop through each post from our array of post ids */ | |
foreach( $args[ 'posts' ] as $person ) { | |
/* get the taxonomy terms for this taxonomy */ | |
$terms = get_the_terms( | |
$person, | |
$args[ 'taxonomy' ] | |
); | |
/* check we have terms and no errors */ | |
if( $terms && ! is_wp_error( $terms ) ) { | |
/* loop through each term */ | |
foreach( $terms as $term ) { | |
/* add this posts id to the relevant term in our output array */ | |
$output[ $term->name ][] = $person; | |
} | |
} | |
} // end term loop | |
return $output; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment