Search code examples
wordpresscustom-post-typewordpress-plugin-creation

get_post_types() is returning null


I am trying to retrieve the post types and put them into an array with their slug being the index and their label being the value. When I print_r( get_post_types() ); it returns the proper array with data, but when I try to use it like below, it returns null.

function get_posttype_list() {
        $pt_list = [];
        $post_types = get_post_types( array( 'public' => true ) );

        foreach( $post_types as $pt ) {
            $pt_list[ $pt->name ] = $pt->labels->singular_name;
        }
    }

Solution

  • Check the document here. You need to return your $pt_list array.

    function get_posttype_list() {
        $pt_list    = array();
        $post_types = get_post_types( array( 'public' => true ) );
    
        foreach ( $post_types as $pt ) {
            $pt_list[ $pt->name ] = $pt->labels->singular_name;
        }
        return $pt_list;
    }