I want to add a custom template for a custom post ('post_type' => 'matches').

I am writing a plugin.I keep my template in the templates/fp-fixture-template.php file.

Here is the function:

function fixture_template( $template_path ) { 
    if ( get_post_type() == 'matches' ) {
        if ( is_single() ) { 
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin 
            if ( $theme_file = locate_template( array ( 'fp-fixture-template.php' ) ) ) { 
                $template_path = $theme_file; 
            } else { 
                $template_path = plugin_dir_path( FILE ) 
                    . 'templates/fp-fixture-template.php'; 
            } 
        } 
    } 
    return $template_path; 
} 

Here is the filter:

add_filter( 'template_include', 'fixture_template');

Code in the fp-fixture-template.php file:

<?php
 /*Template Name: Matches Template
 */
 if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access
?>
<div id="primary">
    <div id="content" role="main">
    <?php
    $mypost = array( 'post_type' => 'matches', );
    $loop = new WP_Query( $mypost );
    ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post();?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> 
        <?php endwhile; ?>
    </div>      
</div>

2 Answers
2

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 Reply

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