How to include a file using get_template_part() in a plugin?

A very simple question may be, but I’m struggling. In theme development, I worked with get_template_part() many times, and I understand its basics. But when I’s developing a plugin, I wondered using it showing me some errors:

Notice: Use of undefined constant STYLESHEETPATH – assumed ‘STYLESHEETPATH’ in ...\wp-includes\template.php on line 407

and

Notice: Use of undefined constant TEMPLATEPATH – assumed ‘TEMPLATEPATH’ in ...\wp-includes\template.php on line 410

Googling the problem showed a support fix:

  • Use get_template_part() into a plugin – WordPress Support

But that seems a huge workaround – I doubt it. I think that shouldn’t be much complicated. I checked this WPSE and found this line of code:

if ( '' === locate_template( 'loop-mycustomposttype.php', true, false ) )
    include( 'loop-mycustomposttype.php' );

Where there is a PHP include() function. As per as my WordPress knowledge I learned to prefer get_template_part() over PHP include(). Then how exactly I can use a simple get_template_part() in my plugin.

I’m not using any loop or something, I’m just separating (or you may say organizing) my plugin code into different files so that in some cases, I will simply comment them out to drop where they are not necessary. I tried:

get_template_part( 'my', 'special-admin' );

and then after the error, changed it to:

get_template_part( 'my', 'specialadmin' );

But you know that’s not the issue. I’m on local server, using WAMP.

3

get_template_part is a theme function. You can’t load plugin files with that function. Take a look at the source and you will notice the work is done by locate_template. Look at that source and you will see that it always loads from theme directories.

However much you may want to use get_template_part it is the wrong function.

You will need to include your files.

The reason, so it seems to me, for get_template_part is to allow themes to be extended– aka, to ease the creation of child themes. Plugins are not intended to be extended in that way so there is no need for get_template_part or for any plugin equivalent.

Leave a Comment