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

Rad*_*dek 39 php wordpress

我能做那样的事吗?将参数传递给我的函数?我已经研究过add_action doc但是没有弄清楚如何做到这一点.传递两个参数的确切语法是什么样的.特别是如何传递文本和整数参数.

function recent_post_by_author($author,$number_of_posts) {
  some commands;
}
add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
Run Code Online (Sandbox Code Playgroud)

UPDATE

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

jgr*_*aup 44

我能做那样的事吗?将参数传递给我的函数?

是的你可以!诀窍在于你传递给add_action的函数类型以及你对do_action的期望.

  • 'my_function_name'
  • 数组(实例,'instance_function_name')
  • 'StaticClassName :: a_function_on_static_class'
  • 匿名
  • 拉姆达
  • 关闭

我们可以通过关闭来实现.

// 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>';
}
Run Code Online (Sandbox Code Playgroud)

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

$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
Run Code Online (Sandbox Code Playgroud)

匿名与封闭

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' ); 
Run Code Online (Sandbox Code Playgroud)

代理功能类

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例#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
Run Code Online (Sandbox Code Playgroud)

用法示例#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
Run Code Online (Sandbox Code Playgroud)


小智 33

代替:

add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
Run Code Online (Sandbox Code Playgroud)

它应该是:

add_action('thesis_hook_before_post','recent_post_by_author',10,2)
Run Code Online (Sandbox Code Playgroud)

...其中2是参数个数,10是执行函数的优先级.您没有在add_action中列出您的参数.这最初让我失望了.你的功能看起来像这样:

function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
Run Code Online (Sandbox Code Playgroud)

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

do_action( 'name-of-action', $arg1, $arg2 );
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


ree*_*ogi 18

使用类构建自定义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 ....
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Den*_*rov 11

将数据传递给add_action函数的7 种方法

  1. 通过do_action(如果你自己创建动作)
  2. wp_localize_script方法(如果您需要将数据传递给 JavaScript)
  3. use在闭包/匿名/Lamda 函数中使用
  4. 使用箭头函数(PHP 7.4+)
  5. 使用add_filter,apply_filters作为传输(聪明的方式)
  6. global用或破解范围$GLOBALS(如果你绝望的话)
  7. 使用set_transient,get_transient和其他功能作为运输(如果有特殊必需品)

#1 通过do_action

如果您有权访问触发操作的代码,请通过以下方式传递变量do_action

/**
* 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 /*, .... */ );
Run Code Online (Sandbox Code Playgroud)

#2wp_localize_script方法

如果您需要将变量传递给 JavaScript,这是最好的方法。

函数.php

/**
 * Enqueue script
 */
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'my_script', get_template_directory_uri() . '/assets/js/my-script.js', array( 'jquery' ), false, false );
} );

/**
 * Pass data to the script as an object with name `my_data`
 */
add_action( 'wp_enqueue_scripts', function(){
    wp_localize_script( 'my_script', 'my_data', [
        'bar' => 'some data',
        'foo' => 'something else'
    ] );
} );
Run Code Online (Sandbox Code Playgroud)

我的脚本.js

alert(my_data.bar); // "some data"
alert(my_data.foo); // "something else"
Run Code Online (Sandbox Code Playgroud)

基本相同,但没有wp_localize_script

函数.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 );
Run Code Online (Sandbox Code Playgroud)

use#3在闭包/匿名/Lamda 函数中使用

如果您无权访问触发操作的代码,您可以按如下方式滑动数据(PHP 5.3+):

$data1 = '1';
$data2 = '2';
$data3 = '3';

add_action( 'init', function() use ($data1, $data2, $data3) {
    echo $data1 . $data2 . $data3; // 123
});
Run Code Online (Sandbox Code Playgroud)

#4 使用箭头函数(PHP 7.4+)

与 #3 示例基本相同,但更简洁,因为箭头函数涉及父作用域中的变量,而不使用use

$data1 = '1';
$data2 = '2';
$data3 = '3';

add_action( 'init', fn() => print( $data1 . $data2 . $data3 ) ); // prints "123"
Run Code Online (Sandbox Code Playgroud)

#5 使用add_filter,apply_filters作为传输

您可以创建一个函数,add_filter当您调用时它将返回值apply_filters

/**
 * Register the data with the filter functions
 */
add_filter( 'data_1', function() { return '1'; } );
add_filter( 'data_2', function() { return '2'; } );
add_filter( 'data_3', fn() => '3' ); // or in concise way with arrow function

function foo() {
    /**
     * Get the previously registered data
     */
    echo apply_filters( 'data_1', null ) . 
         apply_filters( 'data_2', null ) . 
         apply_filters( 'data_3', null ); // 123
}
add_action( 'init', 'foo'); 
Run Code Online (Sandbox Code Playgroud)

我已经看到很多插件都应用了这种方法。

global#6 用or破解范围$GLOBALS(小孩子的方式)

如果您不担心范围,请使用global示例#1:

$data1 = '1';
$data2 = '2';
$data3 = '3';

function foo() {
    global $data1, $data2, $data3;

    echo $data1 . $data2 . $data3; // 123
}
add_action( 'init', 'foo' );
Run Code Online (Sandbox Code Playgroud)

示例#2使用$GLOBALS代替global

$data1 = '1';
$data2 = '2';
$data3 = '3';

function foo() {
    echo $GLOBALS['data1'] . $GLOBALS['data2'] . $GLOBALS['data3']; // 123
}
add_action( 'init', 'foo' );
Run Code Online (Sandbox Code Playgroud)

#7 使用set_transient, get_transient, set_query_var,get_query_var作为传输

示例#1:假设有一个打印表单的短代码,随后通过 AJAX 提交和处理该表单,并且来自表单的数据必须通过电子邮件发送,该电子邮件应从短代码参数中获取。

  1. 初始化短代码
  2. 解析并打印短代码,记住瞬态参数

--- 在 Ajax 处理程序中 ---

  1. 从瞬态中获取所需参数并发送电子邮件。

例子#2:在Wordpress 5.5出来之前,有人在wp_queryby中传递参数get/set_query_vars,将它们传递给模板部分,这些也可以使用。

将它们混合起来使用。干杯。


hol*_*lsk 7

基本上do_action它放在应该执行操作的位置,它需要一个名称加上你的自定义参数.

当您使用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');
Run Code Online (Sandbox Code Playgroud)

这是它执行的地方

do_action('get_the_data',$author,$number_of_posts);
Run Code Online (Sandbox Code Playgroud)

应该有希望工作.


小智 5

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

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


die*_*rre 1

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

<?php add_action( $tag, $function_to_add, $priority, $accepted_args ); ?> 
Run Code Online (Sandbox Code Playgroud)

我认为你应该将它们作为数组传递。查看示例“接受论证”。

再见