Function get_singular_template in WordPress

wordpress get singular template
19 April 2025

Function get_singular_template in WordPress

The function get_singular_template() is one of the functions used in WordPress that helps us to find the appropriate template for displaying our own custom posts. This function is typically used when you open a post, page, or custom type of writing, it frequently occurs and allows you to find a specific template for that writing or page display.

For each type of content, WordPress can consider templates that are more compatible with that post or page. For example, if you have a post with a specific format, like video or gallery, get_singular_template() should find the template related to that format and display it for us.

An interesting point is that you can also define your own templates. For this reason, this function is very helpful for those who are in the process of developing WordPress themes. By using this function, we can create our own unique display format and provide a better user experience for visitors.

To use this function, you do not need to set any kind of conditional argument. It is enough that you set it in the functions.php file yourself. This function will automatically consider the type of writing and its situation, and will load the appropriate templates accordingly.

Code Example

<?php
// Include the function get_singular_template
function my_custom_template() {
if ( is_singular() ) {
// Load appropriate template
get_template_part( get_singular_template() );
}
}
add_action( 'template_redirect', 'my_custom_template' );
?>

Code Explanation


Code: function my_custom_template() {
This line creates a new function named my_custom_template.
Code: if ( is_singular() ) {
Here, we check if the opened page is a singular page (for example, a post or page) or not.
Code: get_template_part( get_singular_template() );
With this line, we can load the appropriate template by using the get_singular_template() function.
Code: add_action( 'template_redirect', 'my_custom_template' );
Finally, we attach our function to the template_redirect action so that WordPress loads the appropriate template when rendering the page.

FAQ

?

What does the function get_singular_template() do?

?

How can I use get_singular_template() in my functions.php?

?

Can I define specific templates for custom types of writings?

?

How can I see the result of this function's action?