0

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;
        }
    }
2
  • print_r( get_post_types( array( 'public' => true ))); does this return an array?
    – Alex T.
    Commented Dec 27, 2022 at 16:43
  • 3
    I see that you're filling up an array named $pt_list however nothing is done with this variable and there is no return statement, is your code incomplete? Can you update it with the rest of the function? How are you checking that it returns null and where is the code running?
    – Tom J Nowell
    Commented Dec 27, 2022 at 16:44

1 Answer 1

0

You have to return your formatted array. Change the code like below

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

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

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.