Skip to content

Instantly share code, notes, and snippets.

@wpmark
Created June 23, 2015 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmark/9da1176af487d744d2c7 to your computer and use it in GitHub Desktop.
Save wpmark/9da1176af487d744d2c7 to your computer and use it in GitHub Desktop.
Get Posts in Terms Array
<?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