WordPress.org

Ready to get started?Download WordPress

Forums

Get an array of post type name (3 posts)

  1. Syaiful
    Member
    Posted 1 year ago #

    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?

  2. Syaiful
    Member
    Posted 1 year ago #

    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 );
    	}
  3. Mark / t31os
    Moderator
    Posted 1 year ago #

    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;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic