get_template_part from plugin


/**
*Extend WP Core get_template_part() function to load files from the within Plugin directory defined by PLUGIN_DIR_PATH constant
* * Load the page to be displayed 
* from within plugin files directory only 
* * @uses mec_locate_admin_menu_template() function 
* * @param $slug * @param null $name 
*/ 

function mec_get_admin_menu_page($slug, $name = null) {

do_action("mec_get_admin_menu_page_{$slug}", $slug, $name);

$templates = array();
if (isset($name))
    $templates[] = "{$slug}-{$name}.php";

$templates[] = "{$slug}.php";

mec_locate_admin_menu_template($templates, true, false);
}

/* Extend locate_template from WP Core 
* Define a location of your plugin file dir to a constant in this case = PLUGIN_DIR_PATH 
* Note: PLUGIN_DIR_PATH - can be any folder/subdirectory within your plugin files 
*/ 

function mec_locate_admin_menu_template($template_names, $load = false, $require_once = true ) 
{ 
$located = ''; 
foreach ( (array) $template_names as $template_name ) { 
if ( !$template_name ) continue; 

/* search file within the PLUGIN_DIR_PATH only */ 
if ( file_exists(PLUGIN_DIR_PATH . "https://wordpress.stackexchange.com/" . $template_name)) { 
$located = PLUGIN_DIR_PATH . "https://wordpress.stackexchange.com/" . $template_name; 
break; 
} 
}

if ( $load && '' != $located )
    load_template( $located, $require_once );

return $located;
}

Then use the mec_get_admin_menu_page($slug, $name = null); function anywhere in your plugin files like the get_template_part($slug, $name = null) function.

mec_get_admin_menu_page('custom-page','one'); 

The above sample function will look for custom-page-one.php file inside your PLUGIN_DIR_PATH and loads it.

Also I recommend you use:

define('PLUGIN_DIR_PATH', plugin_dir_path(__FILE__));

to define your Plugin Directory Path.

Leave a Comment