Php 我可以通过add_操作将参数传递给我的函数吗?

Php 我可以通过add_操作将参数传递给我的函数吗?,php,wordpress,Php,Wordpress,我可以这样做吗?将参数传递给我的函数?我已经学过了,但还没有弄明白怎么做。传递两个参数的确切语法是什么样的。特别是如何传递文本和整数参数 function recent_post_by_author($author,$number_of_posts) { some commands; } add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2') 更新 在我看来,这似乎是通过某种方式完成的,但如何完

我可以这样做吗?将参数传递给我的函数?我已经学过了,但还没有弄明白怎么做。传递两个参数的确切语法是什么样的。特别是如何传递文本和整数参数

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


在我看来,这似乎是通过某种方式完成的,但如何完成呢?:-)

我很久以前就写过wordpress插件,但我去了wordpress Codex,我认为这是可能的:


我认为应该将它们作为数组传递。在示例“获取参数”下查看


再见

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

当您使用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');
这就是它被执行的地方

do_action('get_the_data',$author,$number_of_posts);
希望能奏效。

而不是:

add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
应该是:

add_action('thesis_hook_before_post','recent_post_by_author',10,2)
…其中2是参数数,10是执行函数的优先级。您没有在添加操作中列出您的参数。这一开始让我大吃一惊。然后,您的函数如下所示:

function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
function my_function() {
  echo 100;
}

add_action('wp_footer', 'my_function');
function my_function($number) {
  echo $number;
}

$number = 101;
add_action('wp_footer', function() { global $number; my_function($number); });
public function your_cool_method($first_param, $second_param, $something_else)
{
    // Do something with the params.
}
add_操作和函数都进入functions.php,您可以使用do_操作在模板文件(例如page.php)中指定参数,如下所示:

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

希望这有帮助。

我遇到了同样的问题,并使用全局变量解决了它。像这样:

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

function myfunction() {
    global $myvar;
}
有点草率,但它可以工作。

使用类构建自定义WP函数 这对于类来说很容易,因为您可以使用构造函数设置对象变量,并在任何类方法中使用它们。举个例子,下面是如何在类中添加元框

// 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 ....
        );
    }
}

如果您考虑构造($ARG)< /> >与Fuffic FoeNeNod($ARG)< /代码>相同,那么您应该能够避免全局变量,并将您需要的所有信息传递给类对象中的任何函数。

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


我对PHP5.3+使用闭包。然后,我可以传递默认值,而不传递全局值。(添加过滤器示例)


好吧,这是旧的,但它没有公认的答案。复苏让谷歌搜索者有了一些希望

如果现有的
add_action
调用不接受如下参数:

function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
function my_function() {
  echo 100;
}

add_action('wp_footer', 'my_function');
function my_function($number) {
  echo $number;
}

$number = 101;
add_action('wp_footer', function() { global $number; my_function($number); });
public function your_cool_method($first_param, $second_param, $something_else)
{
    // Do something with the params.
}
您可以使用匿名函数作为回调函数,将参数传递给该函数,如下所示:

function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
function my_function() {
  echo 100;
}

add_action('wp_footer', 'my_function');
function my_function($number) {
  echo $number;
}

$number = 101;
add_action('wp_footer', function() { global $number; my_function($number); });
public function your_cool_method($first_param, $second_param, $something_else)
{
    // Do something with the params.
}

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

首先从本地作用域传入变量,然后再传入
fn

$fn = function() use($pollId){ 
   echo "<p>NO POLLS FOUND FOR POLL ID $pollId</p>"; 
};
add_action('admin_notices', $fn);
$fn=function()使用($pollId){
echo“未找到轮询ID$pollId的轮询”

; }; 添加行动(‘管理通知’,$fn);
我可以这样做吗?将参数传递给我的函数

是的,你可以!诀窍在于你传递给什么类型的函数,以及你期望从中得到什么

  • “我的函数名”
  • 数组(实例“实例\函数\名称”)
  • '静态类名称::静态类上的函数'
  • 匿名的
  • 兰姆达
  • 关闭

我们可以用一只手来做


匿名与封闭

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' ); 

代理函数类

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;
    }
}
示例用法#1

$proxyFunc=新的proxyFunc(
函数(){
echo“”;print_r(函数获取参数());wp_die();
},
数组(1,2,3),“之后”
);
添加操作('TestProxyFunc',$proxyFunc);
执行操作('TestProxyFunc'、'Hello World'、'再见');//你好,世界,1,2,3
示例用法#2

$proxyFunc=新的proxyFunc(
函数(){
echo“”;print_r(函数获取参数());wp_die();
},//回调函数
数组(1,2,3),//存储的参数
'after',//存储参数的位置
“TestProxyFunc”,/(可选)操作
10、/(可选)优先级
2//(可选)增加操作参数的长度。
);
执行操作('TestProxyFunc'、'Hello World'、'再见');//你好,世界,再见,1,2,3

我制作了一个发送参数和流程的代码

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

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

reset_header();
wp_redirect( $approvalUrl);
您可以看到
do\u action('shutdown')
不接受任何参数,但是
routeRequests
接受任何参数。

do

/**
* Our client code
*
* Here we recieve required variables.
*/
function bar($data1, $data2, $data3) {
    /**
     * It's not necessary that names of these variables match 
     * the names of the variables we pass bellow in do_action.
     */

    echo $data1 . $data2 . $data3;
}
add_action( 'foo', 'bar', 10, 3 );

/**
 * The code where action fires
 *
 * Here we pass required variables.
 */
$data1 = '1';
$data2 = '2';
$data3 = '3';
//...
do_action( 'foo', $data1, $data2, $data3 /*, .... */ );
然后

更多信息

7种将数据传递到
add\u action
功能的方法
  • 通过
    执行操作
    (如果您自己创建操作)
  • wp\u localize\u脚本
    方法(如果需要将数据传递给JavaScript)
  • 在Closures/Anonymous/Lamda函数中使用
    use
  • 使用箭头函数(PHP7.4+)
  • 使用
    add_filter
    apply_filters
    作为传输(巧妙的方式)
  • 使用
    global
    $GLOBALS
    破解范围(如果您不顾一切)
  • 使用
    set_transient
    get_transient
    和其他功能作为传输(在特殊需要的情况下)
  • #1至
    执行操作
    如果您可以访问操作触发的代码,请通过
    do\u action
    传递变量:

    alert(my_data.bar); // "some data"
    alert(my_data.foo); // "something else"
    
    #2
    wp\u本地化\u脚本
    方法 如果需要将变量传递给JavaScript,这是最好的方法

    functions.php

    add_action( 'wp_enqueue_scripts', function(){
        echo <<<EOT
        <script> 
        window.my_data = { 'bar' : 'somedata', 'foo' : 'something else' };
        </script>;
        EOT;
    
        wp_enqueue_script( 'my_script', get_template_directory_uri() . '/assets/js/my-script.js', array( 'jquery' ), false, false );
    }, 10, 1 );
    
    $data1 = '1';
    $data2 = '2';
    $data3 = '3';
    
    add_action( 'init', fn() => print( $data1 . $data2 . $data3 ) ); // prints "123"
    
    我的脚本.js

    $data1 = '1';
    $data2 = '2';
    $data3 = '3';
    
    add_action( 'init', function() use ($data1, $data2, $data3) {
        echo $data1 . $data2 . $data3; // 123
    });
    
    基本相同,但没有
    wp\u本地化\u脚本

    functions.php

    add_action( 'wp_enqueue_scripts', function(){
        echo <<<EOT
        <script> 
        window.my_data = { 'bar' : 'somedata', 'foo' : 'something else' };
        </script>;
        EOT;
    
        wp_enqueue_script( 'my_script', get_template_directory_uri() . '/assets/js/my-script.js', array( 'jquery' ), false, false );
    }, 10, 1 );
    
    $data1 = '1';
    $data2 = '2';
    $data3 = '3';
    
    add_action( 'init', fn() => print( $data1 . $data2 . $data3 ) ); // prints "123"
    
    #4使用箭头函数(PHP 7.4+) 基本上与#3示例相同,但更简洁,因为箭头函数涉及来自父范围的变量,而不使用<
    $data1 = '1';
    $data2 = '2';
    $data3 = '3';
    
    function foo() {
        echo $GLOBALS['data1'] . $GLOBALS['data2'] . $GLOBALS['data3']; // 123
    }
    add_action( 'init', 'foo' );
    
    function recent_post_by_author_related($author,$number_of_posts) {
        // some commands;
    }
    
    function recent_post_by_author() {
        recent_post_by_author_related($foo, $bar);
    }
    add_action('thesis_hook_before_post','recent_post_by_author')
    
    do_action('cool_action_name', $first_param, $second_param);
    
    add_action('cool_action_name', 
        function ($first_param, $second_param) {
            // Assuming you're working in a class, so $this is the scope.
            $this->your_cool_method($first_param, $second_param, 'something_else'); 
        }
    );
    
    public function your_cool_method($first_param, $second_param, $something_else)
    {
        // Do something with the params.
    }