I'm writing a plugin that register a new CPT named "sec-feature". In the following loop in my index.php, I want to load a feature-template.php for this CPT posts. But get_template_part
just locate for the file in theme directory. I want this functionality: if this file doesn't exist in theme directory, locate it on my plugin directory instead.
Is there any way to do this(not by hard coding) or handling output template by the plugin?
$args = array( 'post__in' => array(244,302),
'post_type' => array( 'sec-feature')
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part('feature-template');
endwhile;
EDIT
I use the following code in my plugin, but it works just for single posts. In the loop of posts,it doesn't work.
add_filter( 'template_include', 'include_template_function', 1 );
public function include_template_function( $template_path ) {
if ( get_post_type() == 'sec-feature' ) {
$theme_file = get_stylesheet_directory() .'/feature-template.php';
if ( file_exists($theme_file) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( __FILE__ ) . 'feature-template.php';
}
}
return $template_path;
}