0

I'm trying to get a list of categories if they are used in a Custom Post type. The post type uses the default categories taxonomy. There are also other custom post types that use the same default WP category.

Is it possible to add a meta_query that checks if the category is used in a Custom post_type? eq: custom post type: work.

$work_categorys = get_terms(
 [ 
   'taxonomy' => "category", 
   'hide_empty' => true,
 ]
);

foreach ($work_categorys as $key => $value) { echo '<li data-filter-tag="'.$value->slug.'" class="">'.$value->name.'</li>'; }

2 Answers 2

2

This would work. As posted by @bucketpress.

$someposts = get_posts(
    array(
        'post_type' => 'work',
        'posts_per_page' => -1,
        'fields' => 'ids', // return an array of ids
    )
);

$somepoststerms = get_terms(
    array(
        'taxonomy' => 'category',
        'object_ids' => $someposts,
        'hide_empty' => true,
    )
);
2
  • This worked when I removed the tax_query from $someposts query. If I left it in it returned an empty array. What does that part try to do?
    – Bonttimo
    Commented Jan 29, 2020 at 11:20
  • 1
    Good question, I've tested it too, but doesn't seem necessary for your purposed. I've updates the code to reflect that. Commented Jan 30, 2020 at 12:02
0

To get all terms from all taxonomies assigned to "work" custom post type you can customize your code to look like this

$taxes = array_keys( get_object_taxonomies( 'work', 'objects' ) );
$work_categorys = get_terms(
 [ 
   'taxonomy' => $taxes, 
   'hide_empty' => true,
 ]
);
2
  • I get an error: WP_Error Object Invalid taxonomy. Wouldn't this just return the taxonomies used in a custom post type? not the actual categories eq(name, slug, id...)?
    – Bonttimo
    Commented Jan 29, 2020 at 10:41
  • Yes, the get_object_taxonomies() will return taxonomies assigned to a custom post type, the result you can use in the get_terms() call which will return an array of WP_Term objects, although i am looking your original post again and it seems this might not be what you are looking for after all :/ Commented Jan 29, 2020 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.