How to get current post id of a custom post type in a loop using template singel-{custom type}.php?

I have a custom post type template where am looping through all post. what i am trying is when i go to my custom post page i want to get the current post id in the loop.

So i tried to check if the permalink is same for the post inside the loop if it is same i’ll get the post id of the current post in the loop.

Here is the code i tried

First trying to get the permalink in outside to check it inside the loop

$permalink = get_permalink();

Now i got the current post permalink now i want to get the current post id

if($query->have_posts()) : 
    while ($query->have_posts()) : $query->the_post();
        if(the_permalink()==$permalink){
            echo get_the_ID();
        }else{
            echo "not found";
        }
    endwhile;
    wp_reset_postdata();
endif;

I tried this things in single-{custom-post-name}.php am getting not found.
can anyone give me a way to get the current post id in this template?

1 Answer
1

So you have two loops : the main loop and the second one using $query.

You want to compare if at some point of your second loop there’s a match between current post (inside the loop) and the processed post inside the $query loop.

Am I right ?

Instead of checking permalinks I would propose to check IDs.

So on the first loop you create a variable with the current post id :

$current_post_id = $post->ID;

and in your second loop you just compare :

if($query->have_posts()) : while ($query->have_posts()) : $query->the_post();

    if( $current_post_id === $post->ID ) {
         echo $post->ID; 
    } else {
        echo "not found";
    }

endwhile; wp_reset_postdata(); endif;

Not sure that is what you’re looking for, let us know.

PS: I should add to use a more specific name for your query, just to avoid name collision from a plugin or anything, like $my_prefix_query

Leave a Comment