How to get categories linked in posts for a specific post type

In a plugin I´m making, I need to make filters as a combobox to get all categories linked for posts by a specific post t

In a plugin I´m making, I need to make filters as a combobox to get all categories linked for posts by a specific post type.

For example:

Custom post type : Movie

Categories : "Science fiction", "Horror", "Adventures", "Romance", "Comedy" ...

Post Movie 1 : "Science fiction", "Comedy"

Post Movie 2 : "Adventure", "Comedy"

_______________________________________________

Output : (array of Term Objects) "Science fiction", "Comedy", "Adventure"

In a plugin I´m making, I need to make filters as a combobox to get all categories linked for posts by a specific post type.

For example:

Custom post type : Movie

Categories : "Science fiction", "Horror", "Adventures", "Romance", "Comedy" ...

Post Movie 1 : "Science fiction", "Comedy"

Post Movie 2 : "Adventure", "Comedy"

_______________________________________________

Output : (array of Term Objects) "Science fiction", "Comedy", "Adventure"

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Jun 21, 2019 at 14:00 J.BizMaiJ.BizMai 9002 gold badges10 silver badges30 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I found a custom solution, this is the function :

function get_all_categories_linked_to_post_type( $post_type ) {
    $a_terms = array();
    $the_query = get_posts_by_type($post_type);
    if( !empty( $the_query->posts ) ) {
        foreach ($the_query->posts as $post) {
            $terms = wp_get_post_terms($post->ID, 'category');
            if( !empty( $terms ) ){
                foreach ( $terms as $term ){
                    if (!array_key_exists( $term->term_id, $a_terms)) {
                        $a_terms[ $term->term_id ] = $term;
                    }
                }
            }
        }
    }
    return $a_terms;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381199a4625234.html

相关推荐

  • How to get categories linked in posts for a specific post type

    In a plugin I´m making, I need to make filters as a combobox to get all categories linked for posts by a specific post t

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信