Get main parent category for post (WordPress/Advanced Custom Fields)
I am working with a custom category taxonomy field named ‘category-tax’ in WordPress using Advanced Custom Fields. I am trying to have the main parent category be a button for all parent and child related posts. Having a challenging time figuring out how to get the parent category returned, when the parent category is designated in the post. It seems I am only getting the parent category returned when the child category is designated.
I am working with what appears to be non-native ACF code but am not sure, it sort of functions with this exception but would like it to function as intended. Wondering if anyone could shed some light on how to sort this out?
function getCategoryButtons() {
$postCategories = get_the_category($postID);
$postHTML .= 'div class=buttons';
if ($postCategories[0]-parent != 0) {
$cat = get_category($postCategories[0]-parent);
$postHTML .= 'a href='.get_category_link($cat-cat_ID).''.$cat-name.'/a';
}
$postHTML .= '/div';
return $postHTML;}
If I copy and paste in the following code which I pulled from the ACF site, it returns all parent and child categories so I know that the custom field is working.
$terms = get_terms( 'category' ); if ( ! empty( $terms ) ! is_wp_error( $terms ) ){ echo 'ul';
foreach ( $terms as $term ) {
echo 'li' . $term-name . ' - ' . get_field('short_description', $term-taxonomy . '_' . $term-term_id) . '/li'; }
echo '/ul'; }
I hope this is somewhat clear. Thanks for taking the time.
Topic advanced-custom-fields advanced-taxonomy-queries php categories Wordpress
Category Web