• Currently on my project I need an array of custom post type name. I want my array like this,

    array( 'post' => 'post', 'page' => 'page', 'attachment' => 'attachment' );

    and my code like this to retrieve an array that I expect:

    private function post_type_name_array() {
    		$types_array = array();
    
    		foreach ( get_post_types( array( 'public' => true ), 'objects' ) as $post_types ) {
    			$type_array[] = $post_types->name;
    			$types_array = $type_array;
    		}
    		return $types_array;
    	}

    but the output I get is like this

    array( 0 => 'post', 1 => page, ... );

    Any idea?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Syaiful

    (@syaiful6)

    never mind I just solve that,

    private function post_type_name_array() {
    		$types_array = array();
    
    		foreach ( get_post_types( array( 'public' => true ), 'objects' ) as $type ) {
    			$type_array[] =  $type->name;
                            $combine_a = $type_array;
                            $combine_b = $type_array;
    		}
    		return array_combine( $combine_a, $combine_b );
    	}

    There’s an example of getting just names for post types on the documentation page.

    http://codex.wordpress.org/Function_Reference/get_post_types

    Having said that, you appear to want the post type name as the array key aswell as the value, i’d personally just create the array as you loop the types, like so..

    private function post_type_name_array() {
    	$post_types = array();
    	$types = get_post_types( array( 'public' => true ), 'names' );
    	foreach( $types as $post_type )
    		$post_types[$post_type] = $post_type;
    	return $post_types;
    }

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get an array of post type name’ is closed to new replies.