Using WordPress ‘loop_end’ PHP action

The loop_end WordPress PHP action fires once the loop has ended.

Usage

add_action('loop_end', 'my_custom_function');

function my_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_end

Examples

Add a custom message after the loop

Add a message after the loop has ended on a specific post type.

add_action('loop_end', 'add_custom_message');

function add_custom_message($query) {
    if ($query->is_main_query() && is_post_type_archive('product')) {
        echo '<strong>Thanks for browsing our products!</strong>';
    }
}

Show related posts based on categories after the loop has ended.

add_action('loop_end', 'display_related_posts');

function display_related_posts($query) {
    if ($query->is_main_query() && is_single()) {
        // Get the current post's categories
        $categories = get_the_category();

        // Get related posts based on the categories
        $related_posts = new WP_Query(array(
            'category__in' => wp_list_pluck($categories, 'term_id'),
            'posts_per_page' => 3,
            'post__not_in' => array(get_the_ID())
        ));

        // Display the related posts
        if ($related_posts->have_posts()) {
            echo '<h3>Related Posts:</h3>';
            echo '<ul>';
            while ($related_posts->have_posts()) {
                $related_posts->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul>';
        }
    }
}

Add pagination after the loop

Display pagination after the loop has ended on a custom post type archive page.

add_action('loop_end', 'add_custom_pagination');

function add_custom_pagination($query) {
    if ($query->is_main_query() && is_post_type_archive('portfolio')) {
        echo paginate_links();
    }
}

Display a custom message if no posts found

Show a custom message if no posts are found after the loop has ended.

add_action('loop_end', 'display_no_posts_message');

function display_no_posts_message($query) {
    if ($query->is_main_query() && !$query->have_posts()) {
        echo '<strong>No posts found. Please check back later.</strong>';
    }
}

Reset post data after the loop

Manually reset the post data after the loop has ended.

add_action('loop_end', 'reset_post_data_custom');

function reset_post_data_custom($query) {
    if ($query->is_main_query()) {
        wp_reset_postdata();
    }
}