wordpress loop over posts but exclude current post

To exclude the current post while looping over posts in WordPress, you can use the following code within the loop:

<?php
$current_post_id = get_the_ID();

$args = array(
    'post__not_in' => array($current_post_id),
    'post_type' => 'post',
    'posts_per_page' => 5
);

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    // The code to display the post content goes here
endwhile;

wp_reset_postdata();
?>

This code first retrieves the current post's ID using get_the_ID(). It then sets up the query arguments in the $args array, including the 'post__not_in' parameter to exclude the current post by its ID. After that, it initializes the loop using WP_Query, loops over the posts and displays their content, and finally resets the post data using wp_reset_postdata() to ensure that the global post data is restored to its original state.