'How to create a individual template for page or post in custom plugin?

I've have a template inside my plugins directory (quiz-template.php). I need to assign it to a page. I don't want to create template inside theme directory. Everything should be done by my custom plugin only. How can I achieve this ?


function wpse255804_add_page_template ($templates) {
    $templates['quiz-template.php'] = 'Quiz Template';
    return $templates;
    }

add_filter ('theme_page_templates', 'wpse255804_add_page_template');


function wpse255804_redirect_page_template ($template) {
    if ('quiz-template.php' == basename ($template))
        $template = WP_PLUGIN_DIR . '/templates/my-custom-template.php';
    return $template;
    }

add_filter ('page_template', 'wpse255804_redirect_page_template');

Template is showing in (Page Attributes) Template dropdown and saving also.

But content which is written in template file (quiz-template.php) is not coming on frontend.


I've also used below code but it is throwing errors

Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\wordpress2\wp-includes\template-loader.php on line 106

Warning: include(http://localhost/wordpress2/wp-content/plugins/mockTest//templates/quiz-template.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\wordpress2\wp-includes\template-loader.php on line 106

Warning: include(): Failed opening 'http://localhost/wordpress2/wp-content/plugins/mockTest//templates/quiz-template.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\wordpress2\wp-includes\template-loader.php on line 106

function wpse255804_add_page_template ($templates) {
    $templates['quiz-template.php'] = 'QUiz Template';
    return $templates;
    }
add_filter ('theme_page_templates', 'wpse255804_add_page_template');


function wpse255804_redirect_page_template ($template) {
    $post = get_post();
    $page_template = get_post_meta( $post->ID, '_wp_page_template', true );
    if ('quiz-template.php' == basename ($page_template))
        $template = PLUGIN_URL . '/templates/quiz-template.php';
    return $template;
    }
add_filter ('page_template', 'wpse255804_redirect_page_template');



Solution 1:[1]

Well, I suggest this way

function custom_quiz_template()
{
ob_start();
require_once "quiz-template.php";
return ob_get_clean();
}
add_shortcode('custom_quiz_template', 'custom_quiz_template');

and then in your page just add to the content the shortcode

[custom_quiz_template]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cristino