为什么我在主页时获得post id数据

I am trying to create a loop that will recognize the current post id and add a class to it in the menu bar.

this is the code I am using to get the post id value:

wp_reset_query();
$post = $wp_query->post;
$current_project = $post->ID;
echo $current_project; 

this code is working, but the problem is that it also retrieves post id data when I am in the homepage with no posts displaying or queried. It shows the first post's id in order and adds a class to the post's link although it is not currently displayed.

how can I solve this?

In WP Admin, have you set the homepage to a static page? If so then $wp_query->post; will be populated with post data. In your case the homepage will be a post of type 'page'.