I am working on a custom plugin. I created a custom post type inside my plugin. Now, for single posts I want to serve a custom template using my custom plugin without touching any theme file. The problem I am facing is that inside single post file, I can't use get_header() or get_footer() functions which is justified because these functions are meant for themes.
What other options I have to fetch theme's header and footer for my custom template for single post in my custom plugin?
This is the code I have so far which does not work:
<?php
function include_theme_header() {
$header_path = get_template_directory() . '/header.php';
if (file_exists($header_path)) {
ob_start(); // Start output buffering to capture the header content
include($header_path);
$header_content = ob_get_clean(); // Get the captured header content and clean the buffer
// Output or use $header_content as needed
echo $header_content;
}
}
function include_theme_footer() {
$footer_path = get_template_directory() . '/footer.php';
if (file_exists($footer_path)) {
ob_start(); // Start output buffering to capture the header content
include($footer_path);
$footer_content = ob_get_clean(); // Get the captured header content and clean the buffer
echo $footer_content;
}
}
//SERVE CUSTOM TEMPLATE FOR EVENTS CUSTOM POST TYPE SINGLE POST
function custom_post_type_template($template) {
global $post;
// Check if this is a single post of your custom post type
if ($post->post_type == 'event') {
// Include the header
include_theme_header();
// Include your custom content
include(plugin_dir_path(__FILE__) . 'templates/single-event.php');
// Include the footer
include_theme_footer();
// Prevent WordPress from loading the default template
exit;
}
return $template;
}
add_filter('template_include', 'custom_post_type_template');
?>