Change page elements based on geolocation We would like to geolocate visitor IP addresses, and for US-based addresses render a portion of the page to display state-specific options. I actually have the PHP working well to pull the 2-letter state value from a Geocoding API, but am wondering the best way to plug that into Craft PRO.

I'm assuming the logic should look something like this in the end:


Check user for geo-cookie.
If not present, geolocate the user with their 2-letter abbreviation and set the geo-cookie.
If present, read the geo-cookie.
With that value in hand, render page elements accordingly, using the 2-letter abbreviation as a filter. If the user has no 2-letter value (perhaps an international user), present some fall-back "default" content in those areas of the page. (And yes, I am well aware that these services aren't 100% accurate but some providers are fairly close and we can live with that.)


I have found Khalwat's cookie plugin for Craft, which looks like it should suit nicely. But as a newbie to both Craft and Twig, how do I now bring it all together? 

OR should we just adapt Craft PRO's localization options for this instead, since it's built in? And if so, how would we pass the 2-letter value along to use that?
Let's get the easy question out of the way first... Don't use Craft's localization to handle this task. While the localization feature is amazing and powerful, it doesn't fit the needs you're describing. Localization is mainly geared towards handling different languages for different countries.

So what's the best way to handle this? Fortunately, it sounds like you've already worked out the hard part:


  I actually have the PHP working well to pull the 2-letter state value from a Geocoding API


All that's left now is to integrate that business logic into your Craft site! There are a few different ways to approach this, but I'll lay it out in a way that's simple, straightforward, and best fits your current scenario...


Grab and install the Business Logic plugin (unless you've already got a custom plugin installed, in which case you can just build on that).
Create a new function in the Variable file. Let's name it something like detectState.
Put all of your existing PHP logic into that function. You can even get, set, and check your cookies straight from this function. Using a separate cookie plugin may not even be necessary in this situation, since it's easy to manage cookies directly from PHP.
Have your function return the 2-letter state code.
In Twig, you'd call your new function similarly to this:

{% set stateCode = craft.businessLogic.detectState %}



Voila! You can now use stateCode to handle whatever Twig switching logic you need.