WordPress: Pass variables by reference with apply_filter

WordPress has this great filtering system which allows you to write plugins. Yesterday, I was writing a plugin that has the ability for other plugins to change it's behaviour.

For the particular functionality, it would be very nice to use two parameters, which should both be changable.

Standard PHP

In standard PHP, you could do:

function doit($in, &$var2){
    $var2=true;
    return $in+1;
}
 
$changed=false;
echo doit(1,$changed);
echo $changed;

Pass by reference: Not working with WordPress

The WordPress apply_filter and add_filter functions do not allow variable passing by reference. Therefore, the following code will not work.

function doit($in, &$var2){
    $var2=true;
    return $in+1;
}
 
add_filter('myfilter','doit',10,2);
$changed=false;
echo apply_filters('myfilter',1,$changed);
echo $changed;

Dirty solution

You could use $GLOBALS to overcome this problem. I would not recommend this method, as it's not flexible, not safe to re-use and requires the function and the main code to be synchronized.

function doit($in){
    global $changed;
    $changed=true;
    return $in+1;
}
 
add_filter('myfilter','doit');
$changed=false;
echo apply_filters('myfilter',1);
echo $changed;

The good solution

The correct solution to this problem, is to combine all variabled in one array, and use this array as the first variable.

Example 1: For a few parameters

function doit($in){
    list($in,$var2)=$in;
    $var2=true;
    return array($in,$var);
}
 
add_filter('myfilter','doit');
$changed=false;
list($in,$changed)=apply_filters('myfilter',array(1,$changed));
echo $in;
echo $changed;

Example 2: For more complex situations

function doit($in){
    $in['changed']=true;
    $in['in']+=1;
    return $in;
}
 
add_filter('myfilter','doit');
$changed=false;
$in=1;
extract(  apply_filters('myfilter',compact('in','changed'))  );
echo $in;
echo $changed;

This last method may impose a security risk if you use third party plugins.

© GeekLabInfo WordPress: Pass variables by reference with apply_filter is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info

1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 3.71 out of 5)
Loading...

2 comments on “WordPress: Pass variables by reference with apply_filter”

  1. Nice trick and good call. Also, not only arrays but objects as well can be used to pass by reference into filters and action hooks. Also this avoids the hassle of having to match up and maintain the number of arguments when setting up the add_filters() hook registration (the 4th parameter in the function call).

  2. This is an old post. Nowadays you can use the do_action_ref_array function.
    I'm not deleting this post, as the techniques may still be useful for other purposes.

Leave a Reply