Accessing arguments in Custom Variable callback
-
Hello,
I’m programatically creating custom variables using an array and a foreach loop. The array is a list of platforms which corresponds with an meta key in the database which stores the url of the said platform for the current post.
$platform_list = array( array('name' => 'Apple Music', 'slug' => 'apple_music') array('name' => 'Soundcloud', 'slug' => 'soundcloud'), array('name' => 'Spotify', 'slug' => 'spotify') ); foreach($platform_list as $platform) { $slug = $platform['slug']; $name = $platform['name']; rank_math_register_var_replacement($slug, array( 'name' => esc_html__($name, 'rank-math'), 'description' => esc_html__('url for '.$name, 'rank-math'), 'variable' => $slug, 'example' => 'test' ), 'my_callback_function'); } function my_callback_function($var_args = array(), $post = array()) { var_dump($var_args); return '#url'; }
Using a foreach loop to create custom variables works. However I like to access the arguments I pass into rank_math_register_var_replacement inside my callback function, because I need the value of $slug in order to get the corresponding metadata.
The problem is that $var_args is always empty in the callback function.
I have tried the following:
- Setting the callback as a function instead of a string and passing the $slug variable. This does not work because Rank Math uses call_user_func to run the callback function (includes/replace-variables/class-variable.php:188).
- Using $this (like Rank Math its build-in variables) is not possible because we are outside of the object scope.
Relevant functions within Rank Math:
- rank_math_register_var_replacement, template-tags.php:83
- register_replacement, class-manager.php:82
- run_callback, class-variable.php:185
The question:
How can I access the arguments of rank_math_register_var_replacement inside the callback function or pass an argument into the callback function?
Thanks!
- The topic ‘Accessing arguments in Custom Variable callback’ is closed to new replies.