0

I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable.

Here are my current code to get post types:

public function getPostTypes() {
    $excludes = array('attachment');
    $postTypes = get_post_types(
                    array(
                        'public' => true,
                    ),
                    'names'
                 );

    foreach ($excludes as $exclude) {
        unset($postTypes[$exclude]);
    }

    return array_values($postTypes);
}

Thanks!

0

Please try this.

function get_post_tp(){
$args = array(
   'public'   => true,
   '_builtin' => false,

);

$post_types = get_post_types( $args, 'objects' ); 

foreach ( $post_types  as $key => $value ) {

  
  $postArray = json_decode(json_encode($post_types), true);

  $array_key = key($postArray);
  print_r($post_types[$array_key]->taxonomies); // here you can see in taxonomies post_tag is exist or not.
//if exist then push into array otherwise you can skip it.. 
//apply your logic here
   
}

}
add_action('init','get_post_tp');
2
  • Will it work for custom post types too? By default only post is supporting tags but I want to get custom post types too if there are some which also supports tags
    – DaftPlug
    Jul 28 '20 at 11:40
  • Yes ... I have tried in my local system with 5 custom post type and its worked.
    – maulik zwt
    Jul 28 '20 at 11:47
0

Solution is to check for post_tag taxonomy existence.

public function getPostTypes() {
    $excludes = array('attachment');
    $getPostTypes = array_values(
                        get_post_types(
                            array(
                                'public' => true,
                            ),
                            'names'
                        )
                    );

    foreach ($excludes as $exclude) {
        unset($getPostTypes[$exclude]);
    }

    $postTypes = array();
    foreach ($getPostTypes as $postType) {
        get_object_taxonomies($postType);

        if (in_array('post_tag', get_object_taxonomies($postType))) {
            $postTypes[] = $postType;
        }
    }

    return $postTypes;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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