For live U.S. retail fuel prices on WordPress, install the OilPriceAPI Fuel Widgets plugin. It adds a Gutenberg block and shortcodes for the national EIA diesel and regular gasoline averages, makes the request on the server, and needs no API key for those public-domain series. Every successful widget shows the EIA observation week, unit, and source.
Install the plugin, then add one of these shortcodes to a post, page, or widget area:
[oilpriceapi_ticker]: weekly national diesel and regular gasoline averages[oilpriceapi_diesel]: weekly national diesel average
The plugin cannot display crude oil or natural gas. For those, or for any other named price code, use the server-side PHP path below: pass an explicit by_code, show the unit and timestamp the API returns, and check the data-use terms on the pricing page before you publish a series on a public page.
The PHP path in one sentence: store the key in wp-config.php or an environment variable, request https://api.oilpriceapi.com/v1/prices/latest?by_code=YOUR_CODE from PHP with Authorization: Token YOUR_API_KEY, cache a valid response in a transient, and render it with a shortcode or template. Never call the external API from browser JavaScript.
If you need a key for the PHP path, new accounts get a 7-day trial with 10,000 requests and no credit card. After that, the Free plan is 50 requests/day. The Developer plan is $19/month for 10,000 requests/month.
Path 1: the OilPriceAPI Fuel Widgets plugin (no API key)
- Install OilPriceAPI Fuel Widgets from the WordPress plugin directory
- Add the block, or the
[oilpriceapi_ticker]or[oilpriceapi_diesel]shortcode - Your WordPress server requests the public EIA retail series at most once per hour
- The page shows the price with its EIA observation week, unit, and source
The plugin keeps a validated one-hour cache. If the service is unavailable it can show the last successful result for up to 48 hours, labeled as a cached copy, and then removes the price instead of showing a stale one. It sends no visitor data and no API credential.
Use it when you want the national weekly diesel or gasoline average on a public page. Widget themes and other embed options are on the widgets page.
Install OilPriceAPI Fuel Widgets · Widget options
Path 2: fetch a named price in PHP
Use this path when you need a specific code the plugin does not cover, or an internal page such as an operations dashboard.
- WordPress needs a price: check the transient cache first
- Cache miss:
GET /v1/prices/latest?by_code=YOUR_CODEwithAuthorization: Token - Validate the response:
price,code,currency,unit, and theobserved_atsource timestamp - Cache the valid response only; never cache an error
- Render the price with the unit and timestamp the API returned
Data-use check first. The pricing page states that EIA retail diesel and gasoline are U.S. public-domain data and that other third-party series are for internal use only. Before you print any other series on a public WordPress page, read the data-use terms.
Store the key outside the theme
Add the key to wp-config.php (or set it as a server environment variable) so it never lands in a theme or plugin repository:
define( 'OILPRICE_API_KEY', 'your-key-here' );
One cached helper function
Put this in a small site plugin or a child theme. It is the only function that calls the API. Everything else reads from it.
/**
* Latest price for one OilPriceAPI code, cached in a transient.
* Returns an empty array on any failure; errors are never cached.
*/
function opa_get_latest_price( $code, $ttl = DAY_IN_SECONDS ) {
$code = strtoupper( preg_replace( '/[^A-Za-z0-9_]/', '', $code ) );
if ( '' === $code ) {
return [];
}
$transient_key = 'opa_latest_' . strtolower( $code );
$cached = get_transient( $transient_key );
if ( false !== $cached ) {
return $cached;
}
$api_key = defined( 'OILPRICE_API_KEY' ) ? OILPRICE_API_KEY : getenv( 'OILPRICE_API_KEY' );
if ( empty( $api_key ) ) {
return [];
}
$url = add_query_arg( 'by_code', $code, 'https://api.oilpriceapi.com/v1/prices/latest' );
$response = wp_remote_get( $url, [
'timeout' => 10,
'headers' => [ 'Authorization' => 'Token ' . $api_key ],
] );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return [];
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$row = is_array( $body ) && isset( $body['data'] ) && is_array( $body['data'] ) ? $body['data'] : [];
foreach ( [ 'price', 'code', 'currency', 'unit' ] as $field ) {
if ( ! isset( $row[ $field ] ) || '' === $row[ $field ] ) {
return [];
}
}
// observed_at is the source observation time (the EIA week for retail
// fuel); created_at is when OilPriceAPI stored the row.
$observed = ! empty( $row['observed_at'] ) ? $row['observed_at'] : ( $row['created_at'] ?? '' );
if ( '' === $observed ) {
return [];
}
$data = [
'price' => (float) $row['price'],
'code' => $row['code'],
'currency' => $row['currency'],
'unit' => $row['unit'],
'observed_at' => $observed,
'source' => $row['source'] ?? '',
];
set_transient( $transient_key, $data, $ttl );
return $data;
}
The explicit by_code matters. Called without it, /v1/prices/latest returns one default code, BRENT_CRUDE_USD, which is a crude price per barrel, not a fuel price per gallon.
The false !== $cached check keeps a valid cached value from being mistaken for a cache miss. The function returns early on a WP_Error, a non-200 status, invalid JSON, or a missing field, so set_transient() only ever stores a complete response.
Pick a TTL that fits the page
| Page type | Suggested TTL | Reason |
|---|---|---|
| Public page or location page | 24 hours (DAY_IN_SECONDS) |
A daily reading is enough |
| Internal operations dashboard | 6 hours (6 * HOUR_IN_SECONDS) |
Intraday visibility without heavy API usage |
| Contract or weekly-cadence page | 7 days (7 * DAY_IN_SECONDS) |
Matches series that update weekly |
Pass the TTL as the second argument, for example opa_get_latest_price( 'GASOLINE_RETAIL_USD', 6 * HOUR_IN_SECONDS ). Match it to the source cadence and always show the returned observed_at date. For weekly EIA series that is the observation week, not the time OilPriceAPI stored the row.
Add a shortcode
The shortcode reads the cached helper and labels the price with the code, currency, unit, source date, and source from the response. Nothing about the unit is hardcoded.
function opa_price_shortcode( $atts ) {
$atts = shortcode_atts( [ 'code' => '' ], $atts, 'opa_price' );
$data = opa_get_latest_price( $atts['code'] );
if ( empty( $data ) ) {
return '<div class="opa-price">Price unavailable.</div>';
}
$amount = number_format( $data['price'], 2, '.', ',' );
$observed = wp_date( 'm/d/Y', strtotime( $data['observed_at'] ) );
ob_start();
?>
<div class="opa-price">
<div class="opa-price-code"><?php echo esc_html( $data['code'] ); ?></div>
<div class="opa-price-value">
<?php echo esc_html( $amount . ' ' . $data['currency'] . ' per ' . $data['unit'] ); ?>
</div>
<div class="opa-price-updated">
As of <?php echo esc_html( $observed ); ?><?php echo $data['source'] ? ' · Source: ' . esc_html( $data['source'] ) : ''; ?>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'opa_price', 'opa_price_shortcode' );
Editors then write [opa_price code="GASOLINE_RETAIL_USD"] in a post, page, shortcode block, or widget area.
Reuse the same data in a template
In theme files, call the helper directly. This template part is complete and closes its markup:
<?php
$data = opa_get_latest_price( 'DIESEL_RETAIL_USD' );
if ( ! empty( $data ) ) :
$amount = number_format( $data['price'], 2, '.', ',' );
$observed = wp_date( 'm/d/Y', strtotime( $data['observed_at'] ) );
?>
<section class="opa-price-panel">
<h2><?php echo esc_html( $data['code'] ); ?></h2>
<p class="opa-price-amount"><?php echo esc_html( $amount . ' ' . $data['currency'] . ' per ' . $data['unit'] ); ?></p>
<p class="opa-price-meta">As of <?php echo esc_html( $observed ); ?></p>
</section>
<?php endif; ?>
Optional: a local REST route for JavaScript
If the front end needs to refresh a price without a page reload, expose the cached helper through a WordPress REST route and let JavaScript read /wp-json/opa/v1/price?code=.... The route returns only cached, non-secret fields, which is why a public permission_callback is acceptable here. It never forwards the API key to the browser.
add_action( 'rest_api_init', function () {
register_rest_route( 'opa/v1', '/price', [
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
return rest_ensure_response( opa_get_latest_price( (string) $request->get_param( 'code' ) ) );
},
'permission_callback' => '__return_true',
] );
} );
Verify the output and fix common problems
Test the cache in this order:
- Delete the transient:
delete_transient( 'opa_latest_gasoline_retail_usd' ); - Load the page once so it fetches live data.
- Reload right away and confirm no new API request was made.
- On a test site, shorten the TTL and confirm the value refreshes after it expires.
Transient expiry is a maximum age, not a promise. An object cache or a cache flush can remove it early, which is why the helper rebuilds the cache whenever it is missing.
| Symptom | Likely cause | Fix |
|---|---|---|
401 Unauthorized |
Wrong header format or inactive key | Send exactly Authorization: Token YOUR_API_KEY and confirm the key is active. |
| Shows a crude price per barrel | No by_code in the request |
Pass by_code explicitly. Without it the endpoint returns BRENT_CRUDE_USD. |
| "Price unavailable" | Request failed, or a field was missing | Log the HTTP status and body once, outside the cache path, then check the code name. |
| Stale output | Old transient or a page-level HTML cache | Delete the transient and purge the page cache. |
429 Too Many Requests |
Cache not hit, or quota used up | Confirm the transient is being set, then check usage in your dashboard. |
For the full response format and error codes, see the API documentation.
Next steps
For the PHP path:
The same data in other tools:
- Excel: How to get oil prices in Excel
- Google Sheets: How to get oil prices in Google Sheets
- Python: Python oil price API tutorial
- Node.js: Node.js oil price API tutorial
FAQs
Should I use the plugin or the API?
Use the plugin for the national weekly EIA diesel and regular gasoline averages on a public page. It needs no API key. Use the PHP path for any other named code, or for internal pages, and check the data-use terms before publishing a non-EIA series.
Where should I store my API key in WordPress?
In wp-config.php or a server environment variable, never in theme or plugin files that go into version control. Make every API call server-side so the key never reaches the browser. Use a separate key for development so you can rotate it without touching production.
How do I clear or refresh the cached price?
The cache lives in your WordPress site, not in the API. Delete the transient with delete_transient(), or lower the TTL you pass to the helper so a new request runs sooner. The plugin manages its own one-hour cache.
Can I show the same cached price in multiple places?
Yes, where your plan's data-use terms allow public display. Fetch the price once through the helper and reuse the cached value in every shortcode, template, and REST response.
Can I publish crude oil or natural gas prices on a public WordPress page?
Not with the plugin. For other series, read the data-use terms on the pricing page first. EIA retail diesel and gasoline are U.S. public-domain data. Other third-party series are for internal use only.