This plugin is a teaching tool designed to show students how to extend WooCommerce with real-world features like Geolocation, API integration, and caching.
The plugin detects a visitor's country via their IP address, converts product prices into their local currency using a real-time exchange rate API, and displays the local price alongside the original price.
Start by creating the plugin header so WordPress recognizes it. Always include a check for ABSPATH to prevent direct access to the file for security.
We use a Singleton Pattern to ensure the plugin class is instantiated only once. This prevents multiple hooks from being registered unnecessarily.
get_instance()method handles the instantiation.__construct()is madeprivate.
Modern WooCommerce uses High-Performance Order Storage (HPOS). We must explicitly declare compatibility using the before_woocommerce_init hook so the merchant doesn't see a warning.
Inside the init method, we check if WooCommerce is active. If not, we bail. This is where we also determine the store's base currency and the visitor's target currency.
- Geolocation: We use
WC_Geolocation::geolocate_ip()to get the visitor's country code. - Mapping: Since WooCommerce doesn't have a built-in "Country to Currency" map, we implement a simple array mapping (e.g.,
BD->BDT,US->USD).
Connecting to an external API on every page load is slow.
- API: We use
wp_remote_get()to fetch rates fromexchangerate-api.com. - Caching: We use the WordPress Transients API (
set_transient,get_transient) to store the rate for 24 hours.
The core feature uses the woocommerce_get_price_html filter.
- Logic: We skip conversion on Cart/Checkout pages (as transactions must remain in the base currency).
- Calculation: Multiply the product price by the fetched exchange rate.
- Formatting: Use
wc_price()to format the local currency correctly.
To keep the original price looking subtle, we enqueue a small bit of CSS using wp_add_inline_style on the woocommerce-general handle.
| Concept | Explanation |
|---|---|
| Action Hooks | plugins_loaded, before_woocommerce_init, wp_enqueue_scripts |
| Filter Hooks | woocommerce_get_price_html - used to modify data before it's displayed. |
| Transients API | A way to store cached data in the database with an expiration time. |
| Geolocation | Detecting user location to provide personalized experiences. |
| API Integration | Using wp_remote_get to communicate with external services. |
- Enable Geolocation: Go to
WooCommerce > Settings > Generaland set "Default customer location" to "Geolocate". - Clear Transients: If you want to force an API refresh, use a plugin like "Transients Manager" or wait 24 hours.
- Variable Products: Check both simple and variable products to see how the price range is handled.
- Checkout: Verify that the price returns to the original currency once the product is added to the cart.
Developed for educational purposes.