Using WordPress ‘get_category_template()’ PHP function

The get_category_template() WordPress PHP function retrieves the path of the category template in the current or parent theme.

Usage

$template_path = get_category_template();

Parameters

  • None

More information

See WordPress Developer Resources: get_category_template()

Examples

Display Category Template Path

Display the category template path for the current category.

$template_path = get_category_template();
echo 'Current category template path: ' . $template_path;

Include Category Template in a Custom Template

Include the category template in a custom template file.

$template_path = get_category_template();
include($template_path);

Add a Custom Filter to Modify Category Template Hierarchy

Add a custom filter to modify the category template hierarchy.

function custom_category_template_hierarchy($templates) {
    array_unshift($templates, 'custom-category.php');
    return $templates;
}
add_filter('category_template_hierarchy', 'custom_category_template_hierarchy');

Check if a Specific Category Template Exists

Check if a specific category template, such as ‘category-news.php’, exists in the current or parent theme.

function specific_category_template_exists($slug) {
    $template = locate_template("category-{$slug}.php");
    return !empty($template);
}

if (specific_category_template_exists('news')) {
    echo 'Category template "category-news.php" exists.';
} else {
    echo 'Category template "category-news.php" does not exist.';
}

Replace Default Category Template with a Custom One

Replace the default category template with a custom one called ‘custom-category.php’ using a filter.

function replace_default_category_template($template) {
    $custom_template = locate_template('custom-category.php');
    return !empty($custom_template) ? $custom_template : $template;
}
add_filter('category_template', 'replace_default_category_template');