Skip to content

Instantly share code, notes, and snippets.

@maugelves
Last active October 28, 2016 19:14
Show Gist options
  • Save maugelves/8e7c604b77688c7e58e4c99361d0879e to your computer and use it in GitHub Desktop.
Save maugelves/8e7c604b77688c7e58e4c99361d0879e to your computer and use it in GitHub Desktop.
Get the latest child category/ies (those who aren't parent) for a specific post
<?php
/**
* Get the latest hierarchical taxonomy children of a post
*
* @author Mauricio Gelves <[email protected]>
* @param $post_id int Post ID
* @return array
*/
function get_last_children_taxonomy_in_post( $post_id, $taxonomy = 'category'){
// Parameter check
if( empty($post_id) || !is_numeric($post_id) ) return false;
//Get all terms associated with post in a hierarchical taxonomy (default 'category')
$terms = get_the_terms( $post_id, $taxonomy );
//Get an array of their IDs
$term_ids = wp_list_pluck( $terms,'term_id' );
//Get array of parents - 0 is not a parent
$parents = array_filter( wp_list_pluck( $terms, 'parent' ) );
//Get array of IDs of terms which are not parents.
$term_ids_last_child = array_diff( $term_ids, $parents );
//Get corresponding term objects
$terms_not_parents = array_intersect_key( $terms, $term_ids_last_child );
return $terms_not_parents;
}
/**
* Get latest children category/ies of a post
*
* @author Mauricio Gelves <[email protected]>
* @param $post_id int Post ID
* @return array
*/
function get_last_children_categories($post_id){
// Parameter check
if( empty($post_id) || !is_numeric($post_id) ) return false;
return get_last_children_taxonomy_in_post( $post_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment