Using WordPress ‘get_single_template()’ PHP function

The get_single_template() WordPress PHP function retrieves the path of a single template in the current or parent theme. This function is applicable to single Posts, single Attachments, and single custom post types.

Usage

$template_path = get_single_template();

Parameters

  • None

More information

See WordPress Developer Resources: get_single_template

Examples

Display a custom single post template

add_filter( 'single_template', 'my_custom_single_template' );

function my_custom_single_template( $template ) {
    global $post;

    // Check for a specific post ID
    if ( $post->ID == 123 ) {
        $new_template = locate_template( array( 'single-custom.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}

Use a different single template for a specific category

add_filter( 'single_template', 'custom_single_template_for_category' );

function custom_single_template_for_category( $template ) {
    if ( in_category( 'my-category' ) ) {
        $new_template = locate_template( array( 'single-my-category.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}

Load a specific single template for a custom post type

add_filter( 'single_template', 'load_single_template_for_custom_post_type' );

function load_single_template_for_custom_post_type( $template ) {
    global $post;

    if ( 'my_custom_post_type' === $post->post_type ) {
        $new_template = locate_template( array( 'single-my-custom-post-type.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}

Display a custom single template based on post format

add_filter( 'single_template', 'load_single_template_for_post_format' );

function load_single_template_for_post_format( $template ) {
    if ( has_post_format( 'gallery' ) ) {
        $new_template = locate_template( array( 'single-gallery.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}

Use a specific single template for posts with a specific tag

add_filter( 'single_template', 'custom_single_template_for_tag' );

function custom_single_template_for_tag( $template ) {
    if ( has_tag( 'my-tag' ) ) {
        $new_template = locate_template( array( 'single-my-tag.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}