2

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?

  • Because you are using get_permalink() outside the loop you might have to pass the post id. Else it returns false and later when you run through the loop it automatically gives you not found! – sri Nov 22 '13 at 14:09
  • Also explaining the bigger cause for why you are doing this should get you more answers and better ones may be. – sri Nov 22 '13 at 14:10
3

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

  • You are right i was looking for the same. Previously i don't know to use the default have post loop. I thought it will fetch all post. but when i try i had known it will fetch current post. So i used get_the_id() and assigned a variable, then used in the query loop. Thanks @Simon – sun Nov 23 '13 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.