Is a way to pass my own parameters to the function in add_filter or add_action. For example take a look in the following code:

function my_content($content, $my_param)
{
do something...
using $my_param here ...
return $content;
}
add_filter('the_content', 'my_content', 10, 1);

Can I pass my own parameter? something like:

add_filter('the_content', 'my_content($my_param)', 10, 1)

or

add_filter('the_content', 'my_content', 10, 1, $my_param)
up vote 74 down vote accepted

By default this is not possible. There are workarounds if you do it the OOP way.
You could create a class to store the values you want to use later.

Example:

/**
 * Stores a value and calls any existing function with this value.
 */
class WPSE_Filter_Storage
{
    /**
     * Filled by __construct(). Used by __call().
     *
     * @type mixed Any type you need.
     */
    private $values;

    /**
     * Stores the values for later use.
     *
     * @param  mixed $values
     */
    public function __construct( $values )
    {
        $this->values = $values;
    }

    /**
     * Catches all function calls except __construct().
     *
     * Be aware: Even if the function is called with just one string as an
     * argument it will be sent as an array.
     *
     * @param  string $callback Function name
     * @param  array  $arguments
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function __call( $callback, $arguments )
    {
        if ( is_callable( $callback ) )
            return call_user_func( $callback, $arguments, $this->values );

        // Wrong function called.
        throw new InvalidArgumentException(
            sprintf( 'File: %1$s<br>Line %2$d<br>Not callable: %3$s',
                __FILE__, __LINE__, print_r( $callback, TRUE )
            )
        );
    }
}

Now you can call the class with any function you want – if the function exists somewhere it will be called with your stored parameters.

Let’s create a demo function …

/**
 * Filter function.
 * @param  array $content
 * @param  array $numbers
 * @return string
 */
function wpse_45901_add_numbers( $args, $numbers )
{
    $content = $args[0];
    return $content . '<p>' . implode( ', ', $numbers ) . '</p>';
}

… and use it once …

add_filter(
    'the_content',
    array (
        new WPSE_Filter_Storage( array ( 1, 3, 5 ) ),
        'wpse_45901_add_numbers'
    )
);

… and again …

add_filter(
    'the_content',
    array (
        new WPSE_Filter_Storage( array ( 2, 4, 6 ) ),
        'wpse_45901_add_numbers'
    )
);

Output:

enter image description here

The key is reusability: You can reuse the class (and in our examples also the function).

PHP 5.3+

If you can use a PHP version 5.3 or newer closures will make that much easier:

$param1 = '<p>This works!</p>';
$param2 = 'This works too!';

add_action( 'wp_footer', function() use ( $param1 ) {
        echo $param1;
    }, 11 
);
add_filter( 'the_content', function( $content ) use ( $param2 ) {
        return t5_param_test( $content, $param2 );
    }, 12
);

/**
 * Add a string to post content
 *
 * @param  string $content
 * @param  string $string This is $param2 in our example.
 * @return string
 */
function t5_param_test( $content, $string )
{
    return "$content <p><b>$string</b></p>";
}

The downside is that you cannot write unit tests for closures.

  • 16
    Not only do you get an up-vote for a quality answer to a problem that should have a built in solution within WP core, you also get one for coming back five months later to update your answer with the PHP 5.3+ closure example. – userabuser Nov 17 '13 at 7:17
  • 1
    Excellent answer! But how can I do to remove this filter created by this anonymous function later? – Vinicius Tavares Aug 12 '14 at 3:33
  • 2
    @ViniciusTavares You can’t. Think before you use it. :) – fuxia Aug 12 '14 at 8:17
  • 4
    Note though that if you save the anonymous function to a variable (eg $func = function() use ( $param1 ) { $param1; }; and add_action( $func, 11);) then you can remove it via remove_action( $func, 11 ); – bonger May 2 '15 at 18:49
  • But its not advisable to use anonymous functions on plugins or themes you are releasing to the world (you can use them on your own projects). Problem with this is that you won't be able to unhook them. What ever approach you decide to go with should be unhook-able later. – Mueyiwa Moses Ikomi Feb 22 at 16:04

Create a function with the needed arguments that returns a function. Pass this function (anonymous function, also known as closure) to the wp hook.

Shown here for an admin notice in wordpress backend.

public function admin_notice_func( $message = '')
{
$class = 'error';
    $output = sprintf('<div class="%s"><p>%s</p></div>',$class, $message);
    $func = function() use($output) { print $output; };
    return $func;
}
$func = admin_notice_func('Message');
add_action('admin_notices', $func);

I know time have passed, but I had some problem with passing my own parameter till I found that the the 4th parameter in add_filter is number of passed parameters including the content to change. So if you pass 1 additional parameter, number should be 2 and not 1 in your case

add_filter('the_content', 'my_content', 10, 2, $my_param)

and using

function my_content($content, $my_param) {...}

if you create your own hook, here is example.

// lets say we have three parameters  [ https://codex.wordpress.org/Function_Reference/add_filter ]
add_filter( 'filter_name', 'my_func', 10, 3 );
my_func( $first, $second, $third ) {
  // code
}

then implement hook:

// [ https://codex.wordpress.org/Function_Reference/apply_filters ]
echo apply_filters( 'filter_name', $first, $second, $third );
  • This doesn't pass information from the registration to the callback. It just says how many parameters the callback can accept. – fuxia May 17 '15 at 22:15

Use php Anonymous functions:

$my_param = 'my theme name';
add_filter('the_content', function ($content) use ($my_param) {
    //$my_param is available for you now
    if (is_page()) {
        $content = $my_param . ':<br>' . $content;
    }
    return $content;
}, 10, 1);

You can always use global couldn't you?

  global $my_param;

The correct, really short and most efficient way of passing whatever number of arguments to WP filters and actions is from @Wesam Alalem here, that uses the closure.

I would only add that you could make it even clearer and much more flexible by separating the actual doer method from anonymous closure. For this you just call the method from the closure as follows (modified example from @Wesam Alalem answer).

This way you can write as long or complicated logic as you wish lexically outside of the closure you use to call the actual doer.

// ... inside some class

private function myMethod() {
    $my_param = 'my theme name';
    add_filter('the_content', function ($content) use ($my_param) {
        // This is the anonymous closure that allows to pass 
        // whatever number of parameters you want via 'use' keyword.
        // This is just oneliner.
        // $my_param is available for you now via 'use' keyword above
        return $this->doThings($content, $my_param);
    }, 10, 2);
}

private function doThings($content, $my_param) {
    // Call here some other method to do some more things
    // however complicated you want.
    $morethings = '';
    if ($content = 'some more things') {
        $morethings = (new MoreClass())->get();
    }
    return $my_param . ':<br>' . $content . $morethings;
}

I was hoping to do the same but since its not possible I guess a simple workaround is to call a different function like add_filter('the_content', 'my_content_filter', 10, 1);

then my_content_filter() can just call my_content() passing any argument it wants.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.