get_template_part() does not work if you call it when you are in a subfolder

Say for example you have a directory like this:

theme
  - subfolder
    - template.php
content-job-listing.php

If I try and call get_template_part like so get_template_part('content', 'job-listing') from the file template.php (note this is just a generic name not that actual name I’m using) it returns NULL.

Similarly, if I use get_template_part('../content', 'job-listing') this also fails to return the template. However, the first one works fine if both are in the same directory.

get_template_part() does not work if you call it when you are in a subfolder of a t

1 Answer
1

get_template_part() will work the same no matter where or how deep you are within your theme. It always includes relative to the theme (or child theme) root.

So if you call the following from anywhere:

get_template_part( 'content', 'job-listing' );

… it will try to load (in order):

  1. child-theme/content-job-listing.php
  2. parent-theme/content-job-listing.php
  3. child-theme/content.php
  4. parent-theme/content.php

To load parts that are in a subdirectory of your theme, just use the path in the first argument:

get_template_part( 'path/to/file', 'optional-slug' );

Leave a Comment