Using WordPress ‘get_singular_template()’ PHP function

The get_singular_template() WordPress PHP function retrieves the path of the singular template in the current or parent template.

Usage

$template_path = get_singular_template();

Parameters

  • None

More information

See WordPress Developer Resources: get_singular_template

Examples

Display the Singular Template Path

This example retrieves and displays the singular template path.

$template_path = get_singular_template();
echo 'Singular template path: ' . $template_path;

Check if Singular Template Exists

This example checks if the singular template exists and displays a message accordingly.

$template_path = get_singular_template();

if (file_exists($template_path)) {
    echo 'Singular template exists.';
} else {
    echo 'Singular template not found.';
}

Load Singular Template

This example loads the singular template if it exists.

$template_path = get_singular_template();

if (file_exists($template_path)) {
    include($template_path);
} else {
    echo 'Singular template not found.';
}

Override Singular Template

This example overrides the default singular template with a custom one.

add_filter('singular_template', 'my_custom_singular_template');

function my_custom_singular_template($template) {
    $custom_template = get_stylesheet_directory() . '/custom-singular.php';

    if (file_exists($custom_template)) {
        return $custom_template;
    }

    return $template;
}

Add Custom CSS Class to Singular Template Body

This example adds a custom CSS class to the body tag on singular pages.

add_filter('body_class', 'add_custom_class_to_singular_template');

function add_custom_class_to_singular_template($classes) {
    if (is_singular()) {
        $classes[] = 'my-custom-class';
    }

    return $classes;
}