Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dotherightthing/fd436eca6a8c97797143048de1defda9 to your computer and use it in GitHub Desktop.
Save dotherightthing/fd436eca6a8c97797143048de1defda9 to your computer and use it in GitHub Desktop.
[Passing a custom variable to a filter or action] #wordpress

Passing a custom variable to a filter or action

Created: ?

I'd like to create a reusable function to register/replace permalink placeholders.

add_filter('post_link', 'wpdtrt_replace_taxonomy_permalink_placeholders', 10, 3);

wpdtrt_replace_taxonomy_permalink_placeholders($permalink, $post_id, $leavename) {
	...

	return $permalink;
}

The filter post_link accepts three arguments, which are populated by WordPress:

  1. $permalink
  2. $post_id
  3. $leavename

But I also need to pass in two arguments of my own:

  1. $taxonomy_name
  2. $placeholder

Anonymous function + use (PHP 5.4+)

Passing parameters to filter and action hooks

$my_var = 'tratata';

add_filter('the_content', function( $content ) use($my_var) {
	return $my_var;
});

Global variable

ParentFunc();
function ParentFunc()
{
  $var = 5;

  function NestedFunc() {
    global $var;
    $var = $var + 5;
    return $var;
  };

  echo NestedFunc();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment