Skip to content

Instantly share code, notes, and snippets.

@nathan-roberts
Last active February 17, 2021 11:41
Show Gist options
  • Save nathan-roberts/317fe4558b9a3dd61f20cf59e2d60e73 to your computer and use it in GitHub Desktop.
Save nathan-roberts/317fe4558b9a3dd61f20cf59e2d60e73 to your computer and use it in GitHub Desktop.
<?php
// Template Logic
function twt_trailer_archive_template($original_template)
{
// Set our post type
$post_type = 'trailer';
// Set the expected path for a override template within the site theme
$file = trailingslashit(get_template_directory()) . "archive-$post_type.php";
$plugin_directory = WP_PLUGIN_DIR . '/' . str_replace(basename(__FILE__), "", plugin_basename(__FILE__));
// Check if we are on the archive page for our template
if (is_post_type_archive($post_type)) {
// Check if there is an override template within our theme
if (file_exists($file)) {
// if override file is found in activate theme then render our archive page using that theme
return trailingslashit(get_template_directory()) . "archive-$post_type.php";
} else {
// if override file is not found then use the template from within our plugin
return $plugin_directory . "templates/archive-$post_type.php";
}
// Check if we on a single page within our post type
} elseif (is_singular($post_type)) {
// Check if there is an override template within our theme
if (file_exists(get_template_directory_uri() . "/single-$post_type.php")) {
// if override file is found in activate theme then render our archive page using that theme
return get_template_directory_uri() . "/single-$post_type.php";
} else {
// if override file is not found then use the template from within our plugin
return plugin_dir_path(__DIR__) . "templates/single-$post_type.php";
}
}
return $original_template;
}
add_action('template_include', 'twt_trailer_archive_template');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment