I am trying to get all categories that are attached to a custom post type in Wordpress.
I have a custom post type named doc_pipeline
and a custom taxonomy named tax_pipeline
. I have been searching for hours on this and I can't put the right functions together to make this happen. To repeat I need to get a category name that is attached to the custom post type only if it is checked. Should be fairly simple, but I am quite lost.
$args = array(
'post_type' => 'doc_pipeline',
'taxonomy' => 'tax_pipeline',
'posts_per_page' => -1
);
$categories = get_categories( $args );
$posts = get_posts($args);
foreach($posts as $post) {
var_dump(is_object_in_term( $post->ID, 'tax_pipeline', 'doc_pipeline'));
}
To get the category name of the post by post id you should use like this. you already have post ID so, you don't have to pass post type.
$cat_array = wp_get_post_terms($post->ID, 'tax_pipeline', array('fields'=>'names'));
and
// To Remove dublicate category from loop, try this.
$unique_terms = array(); // instead of $dupe = 0;
while ( $wp_query->have_posts() ) : $wp_query->the_post();
global $post;
//Ok, Then you have to use like this in your loop.
$cat_array = wp_get_post_terms( $post->ID, 'tax_pipeline', array( 'fields' => 'all' ) );
foreach( $cat_array as $term ) :
if( ! in_array( $term->term_id, $unique_terms ) ):
array_push( $unique_terms, $term->term_id );
echo $term->name;
endif;
endforeach;
endwhile;