• So, I’ve got a hook declared already, I’m trying to add a function call to that hook, and pass a variable:
    add_action(‘wp_hook_sidebar’, ‘displayAd($passedtext)’);

    then i’ve got the function:
    function displayAd($passedText)
    {
    echo $passedText;
    }

    The text doesn’t get passed to the function though. I know that’s not the way it works based on a couple of previous threads I found:
    http://wordpress.org/support/topic/155337
    and
    http://wordpress.org/support/topic/166587

    But, neither of those threads provide an answer. Anybody got a clue how I can get that variable passed? This is driving me nuts

Viewing 2 replies - 1 through 2 (of 2 total)
  • Sorry, it doesn’t work that way.

    All WP really does is save your function name and then call it when do_action(‘wp_hook_sidebar’) is called. Your displayAd function is going to have to get what it needs on its own – from a global variable, a function call, a SQL query, etc…

    Try

    global $passedtext;
    $passedtext = 'foo';

    and elsewhere …

    add_action('wp_hook_sidebar','displayAd');
    
    function displayAd() {
        global $passedtext;
    
        echo $passedtext;
    }

    However, if $passedtext is available in the code that calls do_action() then you CAN pass it (but your example is odd or misleading, why bother if you can just echo it anyway.) However, if your displayAd function is doing a bit more, you can do this:

    do_action('my_hook',$myparameter, $secondparameter);

    and then

    add_action('my_hook', 'my_function');
    function my_function( $param1, $param2 ) {
    ...
    }

    Of course if you’re dealing with an existing WordPress hook, you can only use parameters if it will be passing them, since the add_action has already been inserted into the code. Check here for details:
    http://adambrown.info/p/wp_hooks
    or just open up the core php file that you’re hooking into.

    (And for other options to get stuff to your function, grab a handy PHP book.)

    (Correction – I meant to say the do_action has already been inserted)

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Pass Variable to function in add_action()’ is closed to new replies.