can I pass arguments to my function through add_action?

后端 未结 13 2112
慢半拍i
慢半拍i 2020-11-29 01:07

can I do something like that? to pass arguments to my function? I already studied add_action doc but did not figure out how to do it. What the exact syntax to pass two argum

相关标签:
13条回答
  • 2020-11-29 01:10

    Instead of:

    add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
    

    it should be:

    add_action('thesis_hook_before_post','recent_post_by_author',10,2)
    

    ...where 2 is the number of arguments and 10 is the priority in which the function will be executed. You don't list your arguments in add_action. This initially tripped me up. Your function then looks like this:

    function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
    

    Both the add_action and function go in functions.php and you specify your arguments in the template file (page.php for example) with do_action like so:

    do_action( 'name-of-action', $arg1, $arg2 );
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-29 01:11

    Pass in vars from the local scope FIRST, then pass the fn SECOND:

    $fn = function() use($pollId){ 
       echo "<p>NO POLLS FOUND FOR POLL ID $pollId</p>"; 
    };
    add_action('admin_notices', $fn);
    
    0 讨论(0)
  • 2020-11-29 01:15

    Do

    function reset_header() {
        ob_start();
    }
    add_action('init', 'reset_header');
    

    then

    reset_header();
    wp_redirect( $approvalUrl);
    

    More info https://tommcfarlin.com/wp_redirect-headers-already-sent/

    0 讨论(0)
  • 2020-11-29 01:18

    I use closure for PHP 5.3+. I can then pass the default values and mine without globals. (example for add_filter)

    ...
    $tt="try this";
    
    add_filter( 'the_posts', function($posts,$query=false) use ($tt) {
    echo $tt;
    print_r($posts);
    return  $posts;
    } );
    
    0 讨论(0)
  • 2020-11-29 01:19

    If you want to pass parameters to the callable function, instead of the do_action, you can call an anonymous function. Example:

    // Route Web Requests
    add_action('shutdown', function() {
        Router::singleton()->routeRequests('app.php');
    });
    

    You see that do_action('shutdown') don't accept any parameters, but routeRequests does.

    0 讨论(0)
  • 2020-11-29 01:20

    I ran into the same issue and solved it by using global variables. Like so:

    global $myvar;
    $myvar = value;
    add_action('hook', 'myfunction');
    
    function myfunction() {
        global $myvar;
    }
    

    A bit sloppy but it works.

    0 讨论(0)
提交回复
热议问题