php 我可以通过 add_action 将参数传递给我的函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2843356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:52:01  来源:igfitidea点击:

can I pass arguments to my function through add_action?

phpwordpress

提问by Radek

can I do something like that? to pass arguments to my function? I already studied add_action docbut did not figure out how to do it. What the exact syntax to pass two arguments would look like. In particular how to pass text & integer arguments.

我可以这样做吗?将参数传递给我的函数?我已经研究了add_action 文档,但没有弄清楚如何去做。传递两个参数的确切语法是什么样的。特别是如何传递文本和整数参数

function recent_post_by_author($author,$number_of_posts) {
  some commands;
}
add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')

UPDATE

更新

it seems to me that it is done somehow through do_actionbut how? :-)

在我看来,它是通过do_action以某种方式完成的,但是如何完成?:-)

回答by jgraup

can I do something like that? to pass arguments to my function?

我可以这样做吗?将参数传递给我的函数?

Yes you can! The trick really is in what type of function you pass to add_actionand what you expect from do_action.

是的你可以!诀窍实际上在于您传递给add_action的函数类型以及您对do_action 的期望。

  • ‘my_function_name'
  • array( instance, ‘instance_function_name')
  • ‘StaticClassName::a_function_on_static_class'
  • anonymous
  • lambda
  • closure
  • '我的功能名称'
  • 数组(实例,'instance_function_name')
  • '静态类名::a_function_on_static_class'
  • 匿名的
  • 拉姆达
  • 关闭


We can do it with a closure.

我们可以用闭包来做到这一点。

// custom args for hook

$args = array (
    'author'        =>  6, // id
    'posts_per_page'=>  1, // max posts
);

// subscribe to the hook w/custom args

add_action('thesis_hook_before_post', 
           function() use ( $args ) { 
               recent_post_by_author( $args ); });


// trigger the hook somewhere

do_action( 'thesis_hook_before_post' );


// renders a list of post tiles by author

function recent_post_by_author( $args ) {

    // merge w/default args
    $args = wp_parse_args( $args, array (
        'author'        =>  -1,
        'orderby'       =>  'post_date',
        'order'         =>  'ASC',
        'posts_per_page'=>  25
    ));

    // pull the user's posts
    $user_posts = get_posts( $args );

    // some commands
    echo '<ul>';
    foreach ( $user_posts as $post ) {
        echo "<li>$post->post_title</li>";
    }
    echo '</ul>';
}


Here is a simplified example of a closure working

这是一个闭包工作的简化示例

$total = array();

add_action('count_em_dude', function() use (&$total) { $total[] = count($total); } );

do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );

echo implode ( ', ', $total ); // 0, 1, 2, 3, 4, 5, 6


Anonymous vs. Closure

匿名与封闭

add_action ('custom_action', function(){ echo 'anonymous functions work without args!'; } ); //

add_action ('custom_action', function($a, $b, $c, $d){ echo 'anonymous functions work but default args num is 1, the rest are null - '; var_dump(array($a,$b,$c,$d)); } ); // a

add_action ('custom_action', function($a, $b, $c, $d){ echo 'anonymous functions work if you specify number of args after priority - '; var_dump(array($a,$b,$c,$d)); }, 10, 4 ); // a,b,c,d

// CLOSURE

$value = 12345;
add_action ('custom_action', function($a, $b, $c, $d) use ($value) { echo 'closures allow you to include values - '; var_dump(array($a,$b,$c,$d, $value)); }, 10, 4 ); // a,b,c,d, 12345

// DO IT!

do_action( 'custom_action', 'aa', 'bb', 'cc', 'dd' ); 


Proxy Function Class

代理函数类

class ProxyFunc {
    public $args = null;
    public $func = null;
    public $location = null;
    public $func_args = null;
    function __construct($func, $args, $location='after', $action='', $priority = 10, $accepted_args = 1) {
        $this->func = $func;
        $this->args = is_array($args) ? $args : array($args);
        $this->location = $location;
        if( ! empty($action) ){
            // (optional) pass action in constructor to automatically subscribe
            add_action($action, $this, $priority, $accepted_args );
        }
    }
    function __invoke() {
        // current arguments passed to invoke
        $this->func_args = func_get_args();

        // position of stored arguments
        switch($this->location){
            case 'after':
                $args = array_merge($this->func_args, $this->args );
                break;
            case 'before':
                $args = array_merge($this->args, $this->func_args );
                break;
            case 'replace':
                $args = $this->args;
                break;
            case 'reference':
                // only pass reference to this object
                $args = array($this);
                break;
            default:
                // ignore stored args
                $args = $this->func_args;
        }

        // trigger the callback
        call_user_func_array( $this->func, $args );

        // clear current args
        $this->func_args = null;
    }
}

Example Usage #1

示例用法 #1

$proxyFunc = new ProxyFunc(
    function() {
        echo "<pre>"; print_r( func_get_args() ); wp_die();
    },
    array(1,2,3), 'after'
);

add_action('TestProxyFunc', $proxyFunc );
do_action('TestProxyFunc', 'Hello World', 'Goodbye'); // Hello World, 1, 2, 3

Example Usage #2

示例用法 #2

$proxyFunc = new ProxyFunc(
    function() {
        echo "<pre>"; print_r( func_get_args() ); wp_die();
    },                  // callback function
    array(1,2,3),       // stored args
    'after',            // position of stored args
    'TestProxyFunc',    // (optional) action
    10,                 // (optional) priority
    2                   // (optional) increase the action args length.
);
do_action('TestProxyFunc', 'Hello World', 'Goodbye'); // Hello World, Goodbye, 1, 2, 3

回答by Bart

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:

...其中 2 是参数的数量,10 是执行函数的优先级。您没有在 add_action 中列出您的参数。这最初让我绊倒了。您的函数如下所示:

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:

add_action 和函数都在 functions.php 中,您可以在模板文件(例如 page.php)中使用 do_action 指定参数,如下所示:

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

Hope this helps.

希望这可以帮助。

回答by reekogi

Build custom WP functions with classes

使用类构建自定义 WP 函数

This is easy with classes, as you can set object variables with the constructor, and use them in any class method. So for an example, here's how adding meta boxes could work in classes...

这对于类很容易,因为您可以使用构造函数设置对象变量,并在任何类方法中使用它们。因此,举个例子,这是在类中添加元框的方式......

// Array to pass to class
$data = array(
    "meta_id" => "custom_wp_meta",
    "a" => true,
    "b" => true,
    // etc...
);

// Init class
$var = new yourWpClass ($data);

// Class
class yourWpClass {

    // Pass $data var to class
    function __construct($init) {
        $this->box = $init; // Get data in var
        $this->meta_id = $init["meta_id"];
        add_action( 'add_meta_boxes', array(&$this, '_reg_meta') );
    }
    public function _reg_meta() {
        add_meta_box(
            $this->meta_id,
            // etc ....
        );
    }
}

If you consider __construct($arg)the same as function functionname($arg)then you should be able to avoid global variables and pass all the information you need through to any functions in the class object.

如果您考虑__construct($arg)相同,function functionname($arg)那么您应该能够避免全局变量并将您需要的所有信息传递给类对象中的任何函数。

These pages seem to be good points of reference when building wordpress meta / plugins ->

在构建 wordpress 元/插件时,这些页面似乎是很好的参考点 ->

回答by hollsk

Basically the do_actionis placed where the action should be executed, and it needs a name plus your custom parameters.

基本上do_action是放置在应该执行操作的地方,它需要一个名称加上您的自定义参数。

When you come to call the function using add_action, pass the name of your do_action()as your first argument, and the function name as the second. So something like:

当您使用 add_action 调用函数时,将您的名称do_action()作为第一个参数传递,将函数名称作为第二个参数传递。所以像:

function recent_post_by_author($author,$number_of_posts) {
  some commands;
}
add_action('get_the_data','recent_post_by_author',10,'author,2');

This is where it's executed

这是执行的地方

do_action('get_the_data',$author,$number_of_posts);

Should hopefully work.

应该希望工作。

回答by Sam Bauers

Well, this is old, but it has no accepted answer. Reviving so that Google searchers have some hope.

嗯,这是旧的,但它没有被接受的答案。复兴让谷歌搜索者有了一些希望。

If you have an existing add_actioncall that doesn't accept arguments like this:

如果您有一个add_action不接受这样的参数的现有调用:

function my_function() {
  echo 100;
}

add_action('wp_footer', 'my_function');

You can pass an argument to that function by using an anonymous function as the callback like this:

您可以通过使用匿名函数作为回调将参数传递给该函数,如下所示:

function my_function($number) {
  echo $number;
}

$number = 101;
add_action('wp_footer', function() { global $number; my_function($number); });

Depending on your use case, you might need to use different forms of callback, possibly even using properly declared functions, as sometimes you may encounter trouble with scope.

根据您的用例,您可能需要使用不同形式的回调,甚至可能需要使用正确声明的函数,因为有时您可能会遇到作用域方面的问题。

回答by Miguel

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

我对 PHP 5.3+ 使用闭包。然后我可以传递默认值,而无需全局变量。(以 add_filter 为例)

...
$tt="try this";

add_filter( 'the_posts', function($posts,$query=false) use ($tt) {
echo $tt;
print_r($posts);
return  $posts;
} );

回答by Brandonian

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

首先从本地范围传入 vars,然后通过fn第二个:

$fn = function() use($pollId){ 
   echo "<p>NO POLLS FOUND FOR POLL ID $pollId</p>"; 
};
add_action('admin_notices', $fn);

回答by LukeSideris

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.

有点马虎,但它的工作原理。

回答by dierre

I've wrote wordpress plugin long time ago, but I went to Wordpress Codex and I think that's possible: http://codex.wordpress.org/Function_Reference/add_action

我很久以前写过 wordpress 插件,但我去了 Wordpress Codex,我认为这是可能的:http: //codex.wordpress.org/Function_Reference/add_action

<?php add_action( $tag, $function_to_add, $priority, $accepted_args ); ?> 

I think you should pass them as an array. Look under examples "take arguments".

我认为您应该将它们作为数组传递。查看示例“采取论点”。

Bye

再见

回答by Lucas Bustamante

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

如果要将参数传递给可调用函数,而不是 do_action,则可以调用匿名函数。例子:

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

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

你看到do_action('shutdown')不接受任何参数,但接受routeRequests