1. Create the Custom Template File:
First, create a template file that you want to use as the default template for your custom post type. For example, create a file called single-work.php
(assuming your custom post type is work
).
You can store this file within your plugin’s directory, for example: /my-plugin/templates/single-work.php
.
2. Use the template_include
Filter to Override the Template:
In your plugin, use the template_include
filter to specify the custom template for your custom post type.
function my_plugin_custom_post_type_template( $template ) {
if ( is_singular( 'work' ) ) {
// Define the path to the template file inside your plugin
$plugin_template = plugin_dir_path( __FILE__ ) . 'templates/single-work.php';
// Check if the template file exists
if ( file_exists( $plugin_template ) ) {
return $plugin_template;
}
}
return $template;
}
add_filter( 'template_include', 'my_plugin_custom_post_type_template' );
Example structure of single-work.php
:
Make sure that your custom template file (single-work.php
) follows WordPress’ template structure, including get_header()
, get_footer()
, etc
<?php get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
while ( have_posts() ) :
the_post();
// Custom template content for 'work' post type
the_title( '<h1>', '</h1>' );
the_content();
endwhile;
?>
</main>
</div>
<?php get_footer(); ?>