How to add custom template in plugin?

This plugin looks for page_contact.php from active theme’s folder and uses plugin’s templates/page_contact.php as a fallback.

<?php
/**
 * Plugin Name: Test Plugin
 */

add_filter( 'template_include', 'contact_page_template', 99 );

function contact_page_template( $template ) {
    $file_name="page_contact.php";

    if ( is_page( 'contact' ) ) {
        if ( locate_template( $file_name ) ) {
            $template = locate_template( $file_name );
        } else {
            // Template not found in theme's folder, use plugin's template as a fallback
            $template = dirname( __FILE__ ) . '/templates/' . $file_name;
        }
    }

    return $template;
}

Create page “Contact” and then templates/page_contact.php in your plugins folder. Now you should see your template content instead of normal template.

Leave a Comment