The in_the_loop() WordPress PHP function determines whether the caller is in the Loop.
Usage
if (in_the_loop()) { // Your custom code }
Parameters
- None
More information
See WordPress Developer Resources: in_the_loop()
Examples
Modify Single Post Entry Titles
This code enables you to modify the default output of your entry titles in the Loop.
function wpdocs_modify_single_post_entry_titles($title) { if (is_singular('post') && in_the_loop()) { // Modify $title } return $title; } add_filter('the_title', 'wpdocs_modify_single_post_entry_titles');
Display Custom Content for Single Post
This example displays custom content only for single posts in the Loop.
function wpdocs_custom_content_single_post($content) { if (is_singular('post') && in_the_loop()) { // Add custom content $content .= '<p>Custom content for single posts.</p>'; } return $content; } add_filter('the_content', 'wpdocs_custom_content_single_post');
Add Post Views Counter
This code adds a post views counter to single posts in the Loop.
function wpdocs_post_views_counter($content) { if (is_singular('post') && in_the_loop()) { $post_views = get_post_meta(get_the_ID(), 'post_views', true); $content .= '<p>Post Views: ' . $post_views . '</p>'; } return $content; } add_filter('the_content', 'wpdocs_post_views_counter');
Display Category Information
This example displays the current post’s category information in the Loop.
function wpdocs_display_category_information() { if (in_the_loop()) { $categories = get_the_category(); if (!empty($categories)) { echo 'Categories: '; foreach ($categories as $category) { echo $category->name . ', '; } } } } add_action('loop_start', 'wpdocs_display_category_information');
Add Comment Count to Post Meta
This code adds the comment count to post meta information in the Loop.
function wpdocs_add_comment_count_to_post_meta($post_meta) { if (in_the_loop()) { $comment_count = get_comments_number(); $post_meta .= ' | ' . $comment_count . ' comments'; } return $post_meta; } add_filter('the_meta', 'wpdocs_add_comment_count_to_post_meta');