Search code examples
wordpressgroup-bycustom-post-typetaxonomy

get post types by taxonomies in wordpress


How to get all the post types(not the posts) grouped by taxonomies? Is there any standard wordpress functions?

I want something like this

taxonomy_1 -> post_type_11, post_type_12, post_type_13,  ....
taxonomy_2 -> post_type_21, post_type_22, ....

Solution

  • I have written a query to get the taxonomies and the attached post types as arrays

    $query = "
    SELECT taxonomy, GROUP_CONCAT( DISTINCT `post_type` SEPARATOR ',') AS `post_types`
    FROM wp_term_taxonomy 
    JOIN wp_term_relationships ON wp_term_relationships.`term_taxonomy_id` =  wp_term_taxonomy.`term_taxonomy_id`
    JOIN wp_posts ON wp_term_relationships.`object_id` = wp_posts.`ID` 
    /* you can add other conditions here like - AND post_status = 'published' */
    GROUP BY taxonomy
    ";
    

    then I call this query

    $global wpdb;
    $post_types_by_taxonomies = $wpdb->get_results( $query, OBJECT_K );
    

    now we can loop through the result array

    foreach($post_types_by_taxonomies as $taxonomy => $post_types_as_string){
        $post_types = explode(',', $post_types_as_string->post_types);
        echo '<hr />';
        echo $taxonomy;
        echo '<br />';
        echo '<br />';
        foreach($post_types as $post_type){
            echo $post_type;
            echo '<br />';
        }
    }