WooCommerce echo price in USD for schema

Viewed 75

All my products have prices in USD. But the prices get changed for visitors out of the US (I'm using WooCommerce Multi-currency). When the prices change, so do the prices in the schema.

So, how can I echo the price in USD?

A sample code:

        "offers": [{
        "@type": "Offer",
        "availability": "http://schema.org/<?php echo $product->is_in_stock() ? 'InStock' : 'OutOfStock'; ?>",
        "price": "<?php echo $product->get_price(); ?>",
        "priceValidUntil": "<?php echo date('Y', strtotime('+1 year')); ?>-11-05",
        "priceCurrency": "<?php echo get_woocommerce_currency(); ?>",
        "url": "<?php echo get_permalink( $product->get_id() ); ?>"
    },{
        "@type": "Offer",
        "availability": "http://schema.org/<?php echo $product->is_in_stock() ? 'InStock' : 'OutOfStock'; ?>",
        "price": "<?php $product->get_price_html(); ?>",
        "priceValidUntil": "<?php echo date('Y', strtotime('+1 year')); ?>-11-05",
        "priceCurrency": "USD",
        "url": "<?php echo get_permalink( $product->get_id() ); ?>"
    }],

The "price": "get_price_html(); ?>", is where I want to have price in USD (2nd offer).

1 Answers
add_filter('woocommerce_get_price_html', 'change_currency_for_specific_product', 100, 2);

function change_currency_for_specific_product($price, $product) {
    if (1631818630 == $product->get_id()) { // Change the product ID
        add_filter('woocommerce_currency', function () {
            return 'INR';
        }, PHP_INT_MAX);
        if ($product->is_on_sale()) {
            $price = wc_format_sale_price(wc_get_price_to_display($product, array('price' => $product->get_regular_price())), wc_get_price_to_display($product)) . $product->get_price_suffix();
        } else {
            $price = wc_price(wc_get_price_to_display($product)) . $product->get_price_suffix();
        }
    }
    return $price;
}
Related