Digital agency · Beervelde (Gent) · Drupal & WordPress

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

Blog

23 mei 2015 · 1 min lezen · door Kristof

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):

WordPress

The default list of variables (<http://docs.mainwp.com/available-wordpress-seo-yoast-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 '';
}
  1. 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' );
}
  1. 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!

Lees ook

Hulp nodig bij je website of marketing?

Een vrijblijvend gesprek van 30 minuten: we luisteren naar je doelen, kijken naar je huidige site en vertellen eerlijk wat we zouden doen. Geen verkooppraatje.

Stuur ons een bericht

Waarmee kunnen we helpen?

Vertrouwd door o.a.

Bel onsPlan een gesprek