Pixcharp
All posts
API and product integrations8 min read

How to Show Live Gold Prices on a WordPress or WooCommerce Site

For jewellers: a small PHP plugin that shows gram, quarter and has gold prices on WordPress with a shortcode and ties WooCommerce product prices to gold, without exposing your API key.

Updated: November 27, 2026

Why server-side, and why cached?

The most common mistake on jewellery sites is calling the gold price API straight from theme JavaScript. The API key then shows up in the page source, and anyone can copy it and spend your quota. The right way is to let WordPress fetch the price on the server and show visitors only the finished price.

The second rule is caching. Instead of asking the API on every page view, you keep the prices in a WordPress transient for 60 seconds. Whether your site gets 10 or 10,000 visitors a day, the API sees at most one request a minute. That is about 45,000 requests a month and fits easily in the 200,000-request Starter plan.

Step 1: Add the API key to wp-config.php

Create an API key in the customer dashboard; you can also start with the 7-day trial without a card. Put the key in wp-config.php as a constant, not in the database or theme settings. That keeps it out of the admin screens and it survives a theme change.

In the dashboard, add your hosting server's outbound IP to the IP whitelist so the key cannot be used anywhere else. On shared hosting the outbound IP can change. If requests start getting 403 ip_not_allowed, the error detail shows the address the API saw; add that one to the list.

wp-config.php
// wp-config.php, above the "That's all, stop editing!" line
define('PIXCHARP_API_KEY', 'pxa_live_...');

Step 2: A small plugin that fetches and caches prices

Save the code below as wp-content/plugins/pixcharp-altin/pixcharp-altin.php and activate it on the Plugins screen. A separate plugin instead of the theme's functions.php keeps the code from being wiped by a theme update.

pixcharp_altin_fiyatlari() fetches every price in one GET /v1/prices request, indexes the rows by symbol and keeps them for 60 seconds. If the API cannot be reached, it falls back to the last good data marked as stale and does not retry for a minute, so a short outage neither slows your site down nor leaves the page empty. The last-updated time under the table tells visitors exactly when the price is from.

pixcharp-altin.php
<?php
/**
 * Plugin Name: Pixcharp Live Gold Prices
 * Description: Fetches prices server-side, caches them for 60 seconds and shows them with the [altin_fiyatlari] shortcode.
 */

if (!defined('ABSPATH')) exit;

function pixcharp_altin_fiyatlari(): array
{
    $fiyatlar = get_transient('pixcharp_altin_fiyatlari');
    if (is_array($fiyatlar)) return $fiyatlar;

    $yanit = wp_remote_get('https://api.pixcharp.com/v1/prices', [
        'headers' => ['X-API-Key' => PIXCHARP_API_KEY],
        'timeout' => 10,
    ]);

    if (is_wp_error($yanit) || wp_remote_retrieve_response_code($yanit) !== 200) {
        // Fall back to the last good data marked as stale; do not call the API again on every visit.
        $son = array_map(fn ($f) => ['stale' => true] + $f, get_option('pixcharp_altin_son_fiyatlar', []));
        set_transient('pixcharp_altin_fiyatlari', $son, MINUTE_IN_SECONDS);
        return $son;
    }

    $fiyatlar = [];
    foreach (json_decode(wp_remote_retrieve_body($yanit), true)['data'] ?? [] as $satir) {
        $fiyatlar[$satir['symbol']] = $satir;
    }
    set_transient('pixcharp_altin_fiyatlari', $fiyatlar, MINUTE_IN_SECONDS);
    update_option('pixcharp_altin_son_fiyatlar', $fiyatlar, false);
    return $fiyatlar;
}

add_shortcode('altin_fiyatlari', function ($atts) {
    $atts = shortcode_atts(['semboller' => 'GRAM_ALTIN,CEYREK_YENI,YARIM_YENI,TAM_YENI,HAS'], $atts);
    $adlar = [
        'GRAM_ALTIN' => 'Gram gold', 'CEYREK_YENI' => 'Quarter gold', 'YARIM_YENI' => 'Half gold',
        'TAM_YENI' => 'Full gold', 'ATA_YENI' => 'Ata gold', 'HAS' => 'Has gold', 'AYAR22' => '22 karat gold',
    ];
    $fiyatlar = pixcharp_altin_fiyatlari();
    $satirlar = '';
    $zaman = '';

    foreach (array_map('trim', explode(',', $atts['semboller'])) as $sembol) {
        if (empty($fiyatlar[$sembol])) continue;
        $f = $fiyatlar[$sembol];
        $zaman = max($zaman, $f['asOfUtc']);
        $satirlar .= sprintf(
            '<tr data-sembol="%s"><td>%s</td><td class="alis">%s</td><td class="satis">%s</td></tr>',
            esc_attr($sembol), esc_html($adlar[$sembol] ?? $sembol),
            number_format_i18n($f['alis'], 2), number_format_i18n($f['satis'], 2)
        );
    }
    if ($satirlar === '') return '';

    return '<table class="altin-fiyatlari"><thead><tr><th>Gold</th><th>Buy</th><th>Sell</th></tr></thead><tbody>'
        . $satirlar . '</tbody></table><p class="altin-guncelleme">Last updated: '
        . esc_html(wp_date('H:i', strtotime($zaman))) . '</p>';
});

Step 3: A price table with a shortcode

With the plugin active, type [altin_fiyatlari] on any page, post or widget area. The default table shows gram, quarter, half, full and has gold. For other symbols, use the semboller (symbols) parameter: [altin_fiyatlari semboller="GRAM_ALTIN,CEYREK_YENI,AYAR22"]. The Shortcode block in Elementor, Gutenberg or another page builder works the same way.

For the full list of symbols you can use, call GET /v1/symbols or check the docs. Style the table in your theme's CSS with the .altin-fiyatlari class.

Step 4: Updating prices without a page reload

If visitors stay on the page for a while, the table can refresh itself. The code below adds a small REST route to your site (/wp-json/pixcharp/v1/altin); the browser reads it once a minute and updates the numbers in the table. Because the route reads the same transient, more visitors do not mean more API usage, and the key never reaches the browser.

The route returns only the buy and sell prices of the symbols your site shows. Showing prices on your own site is allowed on every plan, but redistributing the raw data to others as an API breaks the terms of use, so do not turn this route into a public data service.

pixcharp-altin.php
// Add to the end of the same plugin file.
add_action('rest_api_init', function () {
    register_rest_route('pixcharp/v1', '/altin', [
        'methods' => 'GET',
        'permission_callback' => '__return_true',
        'callback' => function () {
            // Only the symbols your site shows; the key and the raw response never reach the browser.
            $gosterilen = ['GRAM_ALTIN', 'CEYREK_YENI', 'YARIM_YENI', 'TAM_YENI', 'HAS'];
            $fiyatlar = array_intersect_key(pixcharp_altin_fiyatlari(), array_flip($gosterilen));
            return array_map(fn ($f) => ['alis' => $f['alis'], 'satis' => $f['satis']], $fiyatlar);
        },
    ]);
});

add_action('wp_footer', function () { ?>
<script>
(function () {
  if (!document.querySelector('.altin-fiyatlari')) return;
  var locale = document.documentElement.lang || undefined;
  var format = { minimumFractionDigits: 2, maximumFractionDigits: 2 };
  setInterval(async function () {
    var yanit = await fetch('<?php echo esc_url(rest_url('pixcharp/v1/altin')); ?>');
    if (!yanit.ok) return;
    var fiyatlar = await yanit.json();
    document.querySelectorAll('.altin-fiyatlari tr[data-sembol]').forEach(function (satir) {
      var f = fiyatlar[satir.dataset.sembol];
      if (!f) return;
      satir.querySelector('.alis').textContent = f.alis.toLocaleString(locale, format);
      satir.querySelector('.satis').textContent = f.satis.toLocaleString(locale, format);
    });
  }, 60000);
})();
</script>
<?php });

Step 5: Tying WooCommerce product prices to gold

For bracelets, necklaces or bullion coins sold by weight, you may want the price to move with gold. The filter below calculates the sale price from the current gold price using the grams and labour you enter in the product's Custom fields box (enable it under Screen Options). The default symbol is the 22 karat (AYAR22) sell price; if you sell gram gold, set altin_sembol to GRAM_ALTIN.

If no current price is available or the data is stale, the product sells at its saved regular price, so give every product a sensible fallback price. The store currency must be TRY. The cart price is recalculated on every page load too, so customers see the current price at checkout. The code covers simple products; for variable products you also need the woocommerce_product_variation_get_price filter. Margin, labour and rounding are your pricing policy: try the cart and checkout on a staging site before going live.

WooCommerce
// Add to the product's Custom fields: altin_gram (e.g. 5), optional altin_sembol (default AYAR22)
// and iscilik_tl (labour per gram, TRY). Always give the product a fallback regular price too.
add_filter('woocommerce_product_get_price', 'pixcharp_altin_urun_fiyati', 10, 2);
add_filter('woocommerce_product_get_regular_price', 'pixcharp_altin_urun_fiyati', 10, 2);

function pixcharp_altin_urun_fiyati($fiyat, $urun)
{
    $gram = (float) $urun->get_meta('altin_gram');
    if ($gram <= 0) return $fiyat; // Products not tied to gold stay as they are

    $sembol = $urun->get_meta('altin_sembol') ?: 'AYAR22';
    $iscilik = (float) $urun->get_meta('iscilik_tl');
    $f = pixcharp_altin_fiyatlari()[$sembol] ?? null;

    // Without a current price, sell at the product's saved price
    if (!$f || !empty($f['stale'])) return $fiyat;

    return round(($f['satis'] + $iscilik) * $gram, 2);
}

Cache plugins, WebSocket and common mistakes

Page cache plugins such as LiteSpeed Cache or WP Rocket can keep HTML for hours, so the table looks old on first load. The refresh code in step 4 solves this; you can also shorten the cache lifetime of your price page.

Opening the WebSocket straight from the visitor's browser means putting the key in the page source; do not do that on a public jewellery site. If you really need second-by-second prices, open the WebSocket in a small process on your own server; the PHP, Node.js and Python guide shows how. For most jewellery sites, a price refreshed once a minute is enough.

Frequently asked questions

Do I need a ready-made plugin to show gold prices on WordPress?

No. The single-file code in this guide is enough. Keeping it in its own plugin file instead of functions.php keeps it safe from theme updates.

Which plan is enough for a jewellery site?

A site that shows prices with a 60-second cache makes about 45,000 requests a month, so the 200,000-request Starter plan is enough. WooCommerce prices read from the same cache and use no extra requests.

How often do prices update?

In this setup the server refreshes prices at most once a minute and the table updates itself once a minute. You can shorten the cache; every refresh uses 1 request of your monthly quota.

Related pages

Try it free for 7 days
Get a quote