Friday, June 18, 2021

How to create YOAST custom variable

 If you wonder how to create custom YOAST variable here is solution:

You have to add following code into functions.php.

First create empty function which will be used to register all YOAST custom variables:

function register_custom_yoast_variables() {}

Now register that function with YOAST so it knows how to load custom variable. Add following code:

add_action('wpseo_register_extra_replacements', 'register_custom_yoast_variables');

Now create function which will return value of your custom variable. For example:

function say_hello() {
    return "hello world";
}

And we are almost ready. Into register_custom_yoast_variables() add code which will actually register function say_hello as custom variable.

Basically add following code:

wpseo_register_var_replacement( '%%say_hello%%', 'say_hello', 'advanced', 'My custom say_hello yoast variable' );

So function register_custom_yoast_variables will now look like this:

function register_custom_yoast_variables() {
    
wpseo_register_var_replacement( '%%say_hello%%', 'say_hello', 'advanced', 'My custom say_hello yoast variable' );
}

Now if you need more custom variables just create php function which will return value and register it in the function register_custom_yoast_variables

No comments: