Template not loading with get_template_part or locate_template

I have this simple template in a my_template.php file:

div class=popup_canvas_container
    pThis is a template I'm gonna load/p
/div

And I implemented this function to load the template from custom shortcode:

public static function load_template($atts) {       
    function load_my_template() {
        ob_start();

        //if ( file_exists(TEMPLATE_MODULE_DIR . 'my-template.php') ) {
        //  include_once( TEMPLATE_MODULE_DIR . 'my-template.php' );
        //}


        get_template_part('my-template');
        //locate_template( TEMPLATE_MODULE_DIR . 'my-template.php', true, true );
        
        return ob_get_clean();
        
        //global $wpdb;                     
        //$current_user_id = $wpdb-get_var( SELECT user_email FROM newk3_users WHERE user_login = 'xxxxxx'  );       
        //$result = div class='box_external'p$current_user_id/p/div;
        //$result = This is return;       
        
        //return $result;
        
    }
    add_shortcode( 'site_template', 'load_my_template' );

If I use include_once the template would load in the page but if I use wordpress's functions like get_template_part or locate_template it doesn't load the template... since with include_function works I thought maybe I missed something else, even if I put also the complete path to the template file.... could you give me a direction?

Thanks in advance to everyone! Cheers Luigi

Topic get-template-part shortcode Wordpress

Category Web


From your comment: (formatted for brevity)

The cute thing is I debugged that TEMPLATE_MODULE_DIR . 'my-template.php' and the path in a plugin's subfolder is right

in fact as I said in my post, with include_once it loads perfectly

So because you said it's in a plugin subfolder (in wp-content/plugins), then as I said in the comment, it's normal if get_template_part() or locate_template() did not load the template.

And that's because locate_template() (which is used by get_template_part()) only searches templates in the active theme's folder in wp-content/themes and wp-includes/theme-compat if necessary, so for templates in other places like a plugin folder, you would need to use require or include, or their "_once" version. Or there's load_template() if you want to use it instead.

Try placing a copy of your my-template.php in the active theme folder and add "test loading from the active theme folder" somewhere in the template, then see if get_template_part() and/or locate_template() now loads the template?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.