Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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>
share|improve this answer
    
This helped quite a lot. Thank you, Simon –  Alex V. Jan 30 '13 at 0:06

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.

share|improve this answer
    
Taking your suggestion, I've changed up my naming convention to posttype-banner. This, by itself outputs what I want: <?php get_template_part( 'parts/dentistry-banner', '' ); ?> –  Alex V. Jan 29 '13 at 23:15
    
I got it set now. Thank you for your help! '<?php get_template_part('parts/banner',$post->post_type); ?>' –  Alex V. Jan 30 '13 at 0:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.