Using get_template_part to retrieve a template file based on current post type

I’m trying to use get_template_part to retrieve a template file based on the current post type (slug) the user is in. The template file just includes an image that is used specific to specific post types.

<?php get_template_part('parts/get_post_type( $post )') ?><p id="t3-splash-title"><?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->labels->singular_name ; ?></p>

The above doesn’t blow up the page, but nothing seems to get output. Not sure what I’m doing wrong here.

Related posts

Leave a Reply

2 comments

  1. There is built in support for that, kind of. While I don’t see anything wrong with your code, try naming your files on the form archive-mytype.php, content-mytype.php etc. and then call get_template_part like this:

    <!--  This will result in including parts/content-mytype.php -->
    <?php get_template_part('parts/content', get_post_type( $post )); ?>
    <p id="t3-splash-title"><?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->labels->singular_name ; ?></p>
    
  2. Your problem here is partly just bad PHP and partly a misunderstanding of get_template_part.

    You are literally asking for a file named “parts/get_post_type( $post )”. Closer to right would be…

    get_template_part('parts/'.get_post_type( $post ));
    

    Since get_post_type returns a boolean on failure I’d lean towards something more like this though…

    $type = get_post_type($post);
    if (!empty($post)) {
       get_template_part('parts/'.$type ));
    } else {
      // something or nothing; your choice
    }
    

    Now get_template_part is going to be looking for file names like “parts/-post-type.php”. It looks for {slug}-{$name}, or parameter1-parameter2, which is probably not what you want. I imagine that your files are actually “parts/post-type.php” so you will need to rethink your naming scheme.