How To Assign A Plugin PHP File As A Page Template In A Specific WordPress Page

In this article, We learn how to assign a plugin PHP file as a page template in a specific WordPress page.

Step 1: Create one simple page in WordPress pages.


Step 2: Create a Custom plugin.
Here is a link – How To Create a Custom WordPress Plugin
Step 3: Now create a file custom template.php in the custom plugin folder to add that file as a template.

Step 4: Use the “template_include” function to set the page template on a specific page.

add_action( 'template_include', 'custom_page_template' );
function custom_page_template( $template ){
}

Step 5: Use the “is_page” condition to include the template on a specific page and also store the file path in the “$page template” variable.

if ( is_page( 'Custom template page' ) ) {
    $page_template = plugin_dir_path(__FILE__) . 'custom_template\custom_template.php'; // your file path
}
else {
    $page_template = $template;
}

Step 6: Here is the full code of the “template_include” function.

add_action( 'template_include', 'custom_page_template' );
function custom_page_template( $template ){
    if ( is_page( 'Custom template page' ) ) {
        $page_template = plugin_dir_path(__FILE__) . 'custom_template\custom_template.php'; // our file path
    }
    else {
        $page_template = $template;
    }
    return $page_template;
}

Here is the result


I hope this blog will solve your issue. If you have any type of issue please add it to the comment box I will solve all issues as soon as possible.

Thank you.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories