0

What is the proper way of returning data to a hook when there is more than one parameter present?

Example

apply_filters('image_downsize', false, $attachment->ID, $size)

Attaching a callback function:

function wpse_test_hook($param1, $param2, $param3){

}
add_filter('image_downsize', 'wpse_test_hook');

How do I return data from my callback, so that it returns properly for the hook to use?

1 Answer 1

4

You can only return one chunk of data from a function. That is a PHP enforced rule. If you need to return multiple pieces of data you need to return an array or an object.

With filters, though, you can't just decide what to return. You have to return what the filter is meant to return. For example, the_content callbacks need to return a string. Returning a array won't work. You'll just get the word "Array" printed in the post body. On the other hand, if you are passed an array you should return an array.

So, while some filter pass in multiple pieces of data, you only get to modify and return one piece, usually the first parameter. In the generic case you'd want:

function wpse_test_hook($param1, $param2, $param3){
    // whatever you need to do
    return $param1;
}
add_filter('some_filter', 'wpse_test_hook');

But check the how the filter is used. In the case of the image_downsize hook two parameters come in-- $id and $size-- but the image_downsize function just returns whatever the callback gives it. That hook, if used, is meant to completely hijack the rest of the function. It is a bit different that more common hooks like the_content. You can still only return one chunk of data and you still have to return the right kind of data or you will certainly cause trouble somewhere.

With actions you can sometimes modify multiple pieces of information, but actions don't return at all so the PHP restriction is not an issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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