Driving me nuts.
I have a shortcode which works -fine- but for one detail. I won’t post the entire thing, but it pulls the content of a post (works fine) then should echo a portion of it to a new DIV in the footer.
I’m doing it this way because, apparently, you can’t pass variables to an anonymous function with add_action.
add_shortcode('tooltip', 'tooltip');
function tooltip( $atts, $content=null) {
$output = '...some stuff from another post.';
//...working fine...
do_action( 'jch_tooltip_func', 'text to put in footer' );
// the text arg is never passed to jch_tooltip_func();
return $output;
}
add_action('wp_footer', 'jch_tooltip_func', 100, 1);
function jch_tooltip_func( $d ) {
echo('<p>DIV TEST:' . $d . 'END</p>' );
return($d);
}
…so ‘text to put in footer’ should be passed to jch_tooltip_func() and then placed my footer via wp_footer. But the argument never gets passed.
Why oh why?
TIA,
—JC
Use a class, store the value you need in the footer in a member variable.
Sample code, not tested:
it doesn’t work because the first parameter provided to
do_action
is not function name but tag name. They work like thisTHE SOLUTION
If your text to be added is static like in the example above, remove the
add_action('wp_footer', ...)
& replace thedo_action
withif your text is dynamic, then you can take one of the 2 approaches
First, use
var_export()
php function in the code of the above solutionSecond, save the variable to some global/static variable(just make sure it’s safe) & then where you used
add_action
above instead of create_function pass the name of the function that will read that variable & output it. A class variable works best for this case but it could be any variable as long as you’re sure it’s not modified by some other pluginI know this is old but here is my answer and it can help anybody who’s having similar challenge as mine. Based on @fuxia code, her code works perfectly but will only display one output. Assuming you have multiple instances of the shortcode on a page, Only one action hook will be added to footer.
If you want to add multiple action based on the number of times your shortcode is used on a page use the code below;
NOTE: If you want to add just one element to footer regardless of how many times the shortcode is used, @fuxia’s answer is what you’d go for.
Tested and Works!
Happy Coding!