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?
$_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