Question

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!

Était-ce utile?

La solution

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');

Autres conseils

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top