WordPress + Woocommerce + Yoast: add a custom variable to the SEO title

Deel deze pagina

A customer asked me to add the price of the viewed product to the page title, so it could be displayed in Google like this (notice the price in the blue title):

The default list of variables ( did not suffice, as there is no link with Woocommerce.

Luckely it is very easy to add some code to your custom theme. Here is how I did it:

1. Add a functions.php file to your (custom) theme (if it does not exist yet).

2. write your custom function which returns the value you want (i.c. the price of the product)

* retrieve_price_replacement()
* Retrieves the price of the current product
* @return string
function retrieve_price_replacement() {
  // Check if the class exists, or we could get errors
  if (class_exists('WC_Product')) {
    $product = new WC_Product(get_the_ID());
    if (isset($product->price)) {
      return "{$product->price} EUR";

  // Fallback: return empty string
  return '';

3. Register your custom function as a variable

* register_custom_extra_replacements()
* Register extra SEO replacements for the page title
function register_custom_extra_replacements() {
  wpseo_register_var_replacement( '%%price%%', 'retrieve_price_replacement', 'advanced', 'Get the price for the loaded product' );

4. Hook the register function on to the action “wpseo_register_extra_replacements”

add_action('wpseo_register_extra_replacements', 'register_custom_extra_replacements');

You can now easily add extra variables by adding them to the register_custom_extra_replacements() function.

All code above goes into the functions.php file.

Happy coding!

Vraag uw gratis websiteanalyse aan!

Brengt uw website niet het rendement die u voor ogen had?
Blijft het aantal klanten op uw website achter?

Vraag dan nu uw gratis website analyse aan en onze expert Louis vertelt u in een 5-minuten video waar de grootste problemen zitten.