While inside the loop, I need to do some calculations with latitudes and longitudes to create a delivery fee based on a distance for each post.

I have a couple hundred posts, but will only have about 20 unique latitude and longitude pairs for each website visitor. To keep from querying the map API for each individual post in the loop, I'm creating cookies that are named with the latitude and longitude pair. This way I can query 20 times (each unique pair), and then save the distance to a unique cookie. Then I can simply see if that unique cookie exists before querying the API.

I'm using setcookie() to create the cookies and if(isset($_COOKIE[****])) to see if the cookie already exists.

The problem I'm having is while the loop is "looping" through the posts, it is setting the cookies, but does not seem to be able to find them. I'm echoing text so I know if a cookie was used or an API was performed, and its not using any cookies. BUT, if I refresh the page, it does no API queries and finds all the cookies. I'm also echoing the variables used to create the cookie names, and all the cookies are named properly. (ie. many are duplicates)

Is there no way for WP to find new cookies as its going through the loop? It seems like after the loop starts, it does not check for any new cookies while its "looping".

Should I (or can I) rather set some kind of global variables (along with creating the cookies) while in the loop? and then I can test to see if the unique variable name already exists instead of looking for a cookie?

  • This seems to be a misunderstanding of how cookies work in PHP, and not anything to do with WordPress. WordPress can't (and wouldn't) "find new cookies" during a loop, because that's not how cookies work. See the accepted answer here for an explanation: stackoverflow.com/questions/18033549/… Mar 20 at 22:39
  • also you provided no code to work with in your question, but Jacob is right, the solution is in the stackoverflow question/answer, you've misunderstood how the $_COOKIES array works and what it contains. You've also implied something else that would prevent cookies from being set, that you're doing it as you go through the loop. Cookies can only be set in the header, so if you've already printed out the theme header etc then it's too late to set cookies via PHP
    – Tom J Nowell
    Mar 20 at 22:44
  • Yes, you're right @JacobPeattie, I did not fully understand cookies...thanks! Mar 21 at 12:51
  • Thanks @TomJNowell Mar 21 at 12:52


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.