Currently I’m trying to get the post type labels plural. In detail:
$GLOBALS['wp_post_types'][ get_current_screen()->post_type ]->labels->name
This is how I’m trying to retrieve it – in the admin UI – using the public wp API functions:
$post_type_name = get_current_screen()->post_type;
$post_type_obj = get_post_type_object( $post_type_name );
get_post_type_labels( $post_type_obj );
The result is the following Error:
Fatal error: Cannot use object of type stdClass as array in D:developmentxampphtdocswp_instwp-includespost.php on line 1209
The problem is that the post type objects labels is also an object, while get_post_type_labels()
calls _get_custom_object_labels()
internally and seems to expect an array.
Fun are the last two lines of the _get_custom_object_labels()
function:
$labels = array_merge( $defaults, $object->labels );
return (object)$labels;
So, am I using the wrong functions? Is the core function wrong? Is this core function only meant to be used during custom post type registration?
Note: Currently on WP version 3.3.2.
Edit:
get_post_type_labels was never intended to be a public function. It is only used internally when registering a post type. See these trac tickets:
Like you mentioned in your question you can get the labels directly from the globals:
Running the function:
Returns:
Alternate use without needing global $wp_post_types:
Running the function:
After doing several tests I have concluded that it is impossible to use get_post_type_labels passing the $post_type_object as specified in the codex. So it seems the only use for
get_post_type_labels
is internally in core when a post type is registered.This works…
This works…
This works too (but why would you bother…)
This also works,
…and does prove that it is entirely possible to use
get_post_type_labels
in themes/plugins passing thepost_type_object
but as I’ve been saying the Codex does not tell you to specify what->attributes
within the object you want to access, hence you receive the error;Fatal error: Cannot use object of type stdClass as array in C:xampphtdocswp-includespost.php on line 1209
Wrapping your code into a function is also a solution should your use-case permit or warrant that.
Any of the above is perfectly acceptable whether its in a function or not, they are still performing the same mechanics and are susceptible to the same problems if the core were to change.
I have a number of different event types and wanted to display the event type next to each title in the loop, so I made a very minor modification to userabuser’s code:
So my complete code now looks like this:
And it works just fine. After each title it displays a hyphen and the plural event type.