The loop_start WordPress PHP action fires once the loop is started.
Usage
add_action('loop_start', 'your_custom_function'); function your_custom_function($query) { // your custom code here }
Parameters
$query
(WP_Query): The WP_Query instance (passed by reference).
More information
See WordPress Developer Resources: loop_start
Examples
Display a custom message at the beginning of the loop
This example displays a custom message at the beginning of the loop.
add_action('loop_start', 'display_custom_message'); function display_custom_message($query) { if ($query->is_main_query()) { echo '<p><strong>Welcome to our blog!</strong></p>'; } }
Add a custom class to the loop container
This example adds a custom class to the loop container.
add_action('loop_start', 'add_custom_loop_class'); function add_custom_loop_class($query) { if ($query->is_main_query()) { echo '<div class="custom-loop-class">'; } } add_action('loop_end', 'close_custom_loop_class'); function close_custom_loop_class($query) { if ($query->is_main_query()) { echo '</div>'; } }
Display ads before the loop
This example displays an ad before the loop starts.
add_action('loop_start', 'display_ads_before_loop'); function display_ads_before_loop($query) { if ($query->is_main_query()) { echo '<div class="ad-container">Your ad content here</div>'; } }
Add a featured post at the beginning of the loop
This example adds a featured post at the beginning of the loop.
add_action('loop_start', 'add_featured_post'); function add_featured_post($query) { if ($query->is_main_query()) { // Get the featured post $featured_post = get_featured_post(); // Display the featured post echo '<div class="featured-post">'; echo '<h2>' . $featured_post->post_title . '</h2>'; echo '</div>'; } }
Display a custom no posts message
This example displays a custom message when no posts are found in the loop.
add_action('loop_start', 'custom_no_posts_message'); function custom_no_posts_message($query) { if ($query->is_main_query() && !$query->have_posts()) { echo '<p><strong>Sorry, no posts found. Please check back later!</strong></p>'; } }