0

So I am writing a plugin and I am wanting to assign a custom template that exist within my plugin directory to a registered CPT (features). I have cpt-features-template.php as the file name located in my plugin folder root.

Can I do something like:

add_filter('single_template', function($original){
  global $post;
  //$post_name = $post->post_name;
  $post_type = $post->post_type;
  $base_name = 'custom-' . $post_type . '-template.php';
  $template = locate_template($base_name);
  if ($template && ! empty($template)) return $template;
  return $original;
});

Above code referenced from Can I assign a template to a custom post type?

  • the file cpt-features-template.php is in your plugin directory ? – mmm Oct 13 '17 at 16:53
  • @mmm yes it is. – samjco Oct 13 '17 at 20:53
1

locate_template search template only in themes then to use a file outside themes, you can use the filter template_include like that

add_filter("template_include", function ($template) {


    $post = get_queried_object();

    if (    is_single()
        &&  ("features" === $post->post_type)
    ) {
        // absolute path to the template file
        $template = __DIR__ . "/../../template/my_features_template.php";
    }


    return $template;

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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