0

I want to get all post types filtered by get_post_types() arguments.

public static function get_post_type()
{
    if(!$post_type = wp_cache_get('post_type', 'dsad'))
    {
        $post_type = get_post_types(array(
            'public' => true,
            'show_ui' => true
        ));
        wp_cache_set('post_type', $post_type, 'dsad');
    }

    return $post_type;
}

However, with this code, it returns this value:

array(3) {
  ["post"]=>
  string(4) "post"
  ["page"]=>
  string(4) "page"
  ["attachment"]=>
  string(10) "attachment"
}

How can I get all of my post types?

2
  • You need to run it after the other post types have been registered. When are you running this code? Commented Aug 14, 2018 at 10:02
  • 4
    caching the value of get_post_types() doesn't speed things up, there's no database query involved, and post types are registered on every page load so that information is already in memory
    – Tom J Nowell
    Commented Aug 14, 2018 at 10:10

2 Answers 2

1

Build in WordPress function for fetching all registered post types: get_post_types()

    <?php
    // hook into init late, so everything is registered
    // you can also use get_post_types where ever.  Any time after init is usually fine.
    add_action( 'init', 'wpse34410_init', 0, 99 );
    function wpse34410_init() 
    {
        $types = get_post_types( [], 'objects' );
        foreach ( $types as $type ) {
            if ( isset( $type->rewrite->slug ) ) {
                // you'll probably want to do something else.
                echo $type->rewrite->slug;
            }
        }
    }
?>
0

This answer can give you an important advice: action init hook and get_post_types

you've to run your function using an hook later than init which is likely the hook used to register your CPT So I think:

add_action('wp_loaded', 'get_post_type');
function get_post_type()
{
    if(!$post_type = wp_cache_get('post_type', 'dsad'))
    {
        $post_type = get_post_types(array(
            'public' => true,
            'show_ui' => true
        ));
        wp_cache_set('post_type', $post_type, 'dsad');
    }

    return $post_type;
}

will work

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.