Home > OS >  WordPress get_post_type, how to display name of label
WordPress get_post_type, how to display name of label

Time:01-10

Hi stackflow community,

I'm fairly new to PHP, so please excuse any mistakes. For Wordpress I have registered a custom post type called ('energy') (see code). I know that with the command <PHP echo get_post_type();><?/>. I can call the name of the post type and I get energy as a result. But I want to call the 'name' that is situated in the 'labels' array. The Energy & Transport - how do I do that? I read it's possible with get_post_type_object(); but, a) I don't know if that's true and b) I don't know how to construct the correct command.

Can anyone please help me to get the correct command? Thanks in advance.

CUSTOM POST TYPE:

register_post_type('energy', array(
  'public' => true,
  'show_in_rest' => true,
  'has_archive' => true,
  'supports' => array('title', 'editor', 'thumbnail'),
  'menu_icon' => 'dashicons-lightbulb',
  'taxonomies'  => array( 'category' ),
  'labels' => array(
    'name' => 'Energy & Transport',
    'add_new_item' => 'Add New Post for Energy & Transport',
    'all_items'=> 'All Energy & Transport Posts',
  )
  ));

CodePudding user response:

So you just need to learn a bit more about objects and arrays really.

You are using the right function get_post_type_object();

In order to access the labels you need to descend the object like so

$energy = get_post_type_object( 'energy' );
echo $energy->labels->name;

Here is the documentation on objects: https://www.php.net/manual/en/language.types.object.php

CodePudding user response:

You can use a combination of get_post_type() and get_post_type_object()

<?php
    // Get the post type  
    $post_type = get_post_type();
    // Get the post type object based on the post type;
    $post_type_object = get_post_type_object( $post_type );

    // Gets the name properties of the post type object.
    $post_type_name = $post_type_object->labels->name;

https://developer.wordpress.org/reference/functions/get_post_type/

https://developer.wordpress.org/reference/functions/get_post_type_object/

  •  Tags:  
  • Related