0

I'm build a custom Wordpress theme using get_template_part to call tiny bits of code. I have file called "masthead.php" that is called using this code:

 <?php get_template_part( 'masthead' ); ?>

This works as expected. However, I would like to create some kind of file hierarchy inside my theme's folder. For example, if there's a file called "custom-masthead.php" use that file first but if the file does not exists, then use "masthead.php".

Is this something that can be accomplished?

EDIT

Following @sabreuse's code I'm trying to make things a little bit more complicated. I would like to print the theme's folder name instead of the $name variable so the folder's name is my main variable before falling into the fallback. I tried this code:

     <?php 
     $theme_name = wp_get_theme();
     get_template_part( 'masthead', 'echo $theme_name->Template;' ); ?>

But this doesn't seem to work. Maybe it's not possible?

EDIT

Got it working:

     <?php 
     $my_theme = wp_get_theme();
     get_template_part( 'masthead', $my_theme->Template ); ?>

Thanks a lot!

Johann

1

Yes, what you describe is already built in to the get_template_part() function:

<?php get_template_part( $slug, $name ); ?> 

Where "masthead" is the general template slug in your example, and "custom" is the more specialized version. You'll have to name your parts slug-name.php (so, masthead-custom.php, rather than custom-masthead.php).

Note that you can also use the value returned by a function for the $name argument -- I do this all the time for things like:

get_template_part( 'content', get_post_type() );

In all cases, if the specialized template part isn't found, masthead.php is used as a fallback.

  • Hi @sabreuse! Thanks for your quick reply. That's is totally correct. Is there a way to print the folders name instead of $name ? Please check my edited post for what I'm trying to accomplish. – Johann Sep 11 '13 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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