1

What is the best way to pass some information from functions.php to a plugin?

I need to give a user the ability to pass a piece of data from their functions.php file to my plugin. (It can be any data, just something that I can check for; it can be a variable's value, or even the fact that a variable was set or a function was defined.)

I tried the suggestion found here:

Pass A Value From Outside To A Plugin Variable

I plugged in that code verbatim:

On your plugin :

 $value = 0;
 $value = apply_filter('get_value_from_function', $value);

Then on functions.php

add_filter('get_value_from_function', 'my_special_value_treatment', 10, 1);
function my_special_value_treatment ($value){
    return 1;
}

But that results in an error:

Fatal error: Call to undefined function apply_filter() in /pathtomyplugin/my-plugin-name/my-plugin-name.php on line 93

I don't understand why that fails. What is the best way to do this?

Edited with this addition:

After changing it to apply_filters(), this still happens... In my plugin:

$value = 0;
$value = apply_filters('get_value_from_function', $value);
if ($value===0) {
    $test_info = 'not_passed';
} else {
    $test_info = 'passed';
};
// $test_info is not_passed
  • Is your $value = apply_filters('get_value_from_function', $value); wrapped in a function? How is that function called? – czerspalace Aug 19 '15 at 18:05
2

Plugins are loaded before the theme which means that your apply_filters won't have any actual callbacks registered to it. Instead, you need to call your apply_filters sometime after the theme has been loaded. Something like this:

/* Your plugin's file: */

add_action( 'init', 'my_lovely_funky_filters' );

function my_lovely_funky_filters() {
    /* Fire our callbacks */
    $value = 0;
    $value = apply_filters( 'get_value_from_function', $value );

    /* Check your $value now */
    /* echo "<pre>{$value}</pre>"; */
}

/* Your functions.php file */

add_filter( 'get_value_from_function', 'my_special_value_treatment', 10, 1 );
function my_special_value_treatment( $value ) {
    /* A little more interesting */
    return (int)$value + 1;
}
  • Thanks. This answers the question I asked. Still can't get some other related things to work, but that will have to be a second question! – hommealone Aug 19 '15 at 18:50
  • So now the value of $value is indeterminate until the init action fires; I can't seem to access its final value from within the plugin file. How can I retrieve it and use it in my plugin file? – hommealone Aug 20 '15 at 0:08
0

This is the correct method - except the function is apply_filters, not apply_filter. Hence your error.

  • Still no good. I added more details above. – hommealone Aug 19 '15 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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