Using WordPress ‘is_singular()’ PHP function

The is_singular() WordPress PHP function determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types).

Usage

is_singular($post_types);

Parameters

  • $post_types (string|string[]|null) (Optional) – Post type or array of post types to check against. Default: ''.

More information

See WordPress Developer Resources: is_singular()

Examples

Check if viewing a regular post

if (is_singular('post')) {
    // Your code here...
}

Check if viewing a custom post type ‘book’

if (is_singular('book')) {
    // Your code here...
}

Check if viewing a post of either custom post types ‘newspaper’ or ‘book’

if (is_singular(array('newspaper', 'book'))) {
    // Your code here...
}

Display different sidebar ads based on singular pages

if (is_singular()) {
    // Show ad #1
} else {
    // Show ad #2
}

Add a custom function to the ‘loop_start’ action hook

add_action('loop_start', 'your_function');
function your_function() {
    if (is_singular()) {
        echo 'Hello World';
    }
}