0

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;
}
2
  • Can you not use archive-sec-feature.php? Commented May 24, 2014 at 20:15
  • Hi Andrew,Thanks for your reply,i think it doesn't matter when you handle this by "template_include" filter. i want that wp,detect automatically template in theme directory,if it doesn't exist,check it in plugin directory. i think archive-sec-feature.php can't handle this individually. Commented May 24, 2014 at 20:20

1 Answer 1

0

There are no hooks in the load sequence triggered by get_template_part() that will help you.

  1. get_template_part()
  2. locate_template
  3. load_template

And locate_template() is hard-coded to look at theme files. I hate to write "you can't do that" answers, but I honestly don't see a way to override what file get_template_part() loads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.