• Resolved Sub_Zero

    (@sub_zero)


    Hi,

    I have a problem understanding the function get_template_part();

    This will include my file ‘page-header.php’ which is in the sub folder ‘templates’:
    get_template_part('templates/page', 'header');

    What are these two parameters used for? Why can’t I use it simply like that:
    get_template_part('templates/page-header.php');
    ?

    Or even better, I could use require_once(); … so what is basically the difference?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Anonymous User 9055193

    (@anonymized-9055193)

    Essentially, get_template_part helps with reusable template code, it’s “theme aware” and performs a few more checks vs simply using require_once.

    Konstantin Kovshenin has the best explanation I’ve read so far…
    https://kovshenin.com/2013/get_template_part/

    This function is good for when you create template pages that you want to call when loading pages.

    If you look at the Codex page for this function, it will tell you this is how you use it:

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

    $slugis required while $name is optional. Now, if you create a template called “cool.php” then $slug = cool and then the code would be:

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

    Now, if the file was called “cool-header.php” then $slug = cool while $name = header and the code would be:

    <?php get_template_part( 'cool', 'header' ); ?>

    Now, if you are dealing with subdirectories and you put the template file in a folder called “partials” with the file called “cool-header.php” then you would use this code:

    <?php get_template_part( 'partials/cool', 'header' ); ?>

    I hope my examples makes sense.

    Thread Starter Sub_Zero

    (@sub_zero)

    Thank you guys! Both posts helped me to understand it. Especially this part was very interesting to know:

    get_template_part( 'navigation', 'above' );
    The first call will look for navigation-above.php in our theme folder, and if that doesn’t exist, it will fall back to navigation.php

    Right. You are welcome! ??

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘What is get_template_part() good for?’ is closed to new replies.