[Resolved] How to display post type in header element

Home Forums Support How to display post type in header element

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #948792
    Whelan

    Hi. Not sure if this was posted successfully, so I’m posting again.

    Is it possible to dynamically display the post type in a header element? I have two post types which use the same header and want to dynamically display the post type, i.e. “Case Study” in the header. What Template Tag do I need to add?

    #949393
    Tom
    Lead Developer
    Lead Developer

    Hi there,

    So are you wanting to output the actual name of the current post type in the header?

    If so, you’ll need to create a shortcode:

    add_shortcode( 'post_type_name', function() {
        $post = get_queried_object();
        $postType = get_post_type_object( get_post_type( $post ) );
    
        if ( $postType ) {
            return $postType->labels->singular_name;
        }
    } );

    Then you could use this in the hero: [post_type_name]

    #949515
    Whelan

    Thanks Tom.

    Yes, I want to output the actual post type name for a header that serves several distinct custom post types.

    Two questions:
    1. Is the shortcode you provided going to be more efficient (in terms of page speed and server resources) than creating a distinct header for each post type and just manually writing the post type for each header?

    2. Can I add the supplied code as a hook and if so, what would be the best location, i.e. wp_head?

    #949884
    Tom
    Lead Developer
    Lead Developer

    1. Yes, this would be more efficient than creating multiple Elements.

    2. The code I supplied should be added using one of these methods: https://docs.generatepress.com/article/adding-php/

    Let me know if you need more info 🙂

    #949991
    Whelan

    OK, thanks a lot Tom.

    PS I still haven’t quite got my head around what can be added to GP Hooks vs what needs to be added via one of the other methods mentioned above. Is there an easy distinction for a WordPress novice such as myself?

    #949999
    Leo
    Staff
    Customer Support

    Hooks is mostly for adding content into specific parts of the page:
    https://docs.generatepress.com/article/hooks-visual-guide/

    The code Tom provided is just to create the shortcode so needs to be added using function. But then you can use hooks to display the shortcode.

    Hope that makes sense 🙂

    #950002
    Whelan

    Yes, that makes sense, thanks.

    #950005
    Leo
    Staff
    Customer Support
Viewing 8 posts - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.