如何将附加参数传递给 wordpress 过滤器? [英] How to pass additional parameter to wordpress filter?

查看:60
本文介绍了如何将附加参数传递给 wordpress 过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

add_filter('wp_list_pages_excludes', 'gr_wp_list_pages_excludes');

function gr_wp_list_pages_excludes($exclude_array) {    
    $id_array=$array('22');
    $exclude_array=array_merge($id_array, $exclude_array);
    return $exclude_array;
}

我是 wordpress 的新手.上面的代码工作正常.但我需要传递额外的参数,比如 $mu_cust_arg 给函数 gr_wp_list_pages_excludes.如何通过 apply_filters 或任何其他方法使用它?任何帮助表示赞赏.

I'm a newbie to wordpress. The above code works fine. But I need to pass additional argument, say $mu_cust_arg to the function gr_wp_list_pages_excludes. How can I make use of it via apply_filters, or any other methods? Any help is appreciated.

提前致谢.

推荐答案

因为 WP 不接受闭包作为回调(至少,对于 add_filter() 肯定不是),简短的回答是你不能".至少,不是以整洁的方式.

Because WP doesn't accept closures as callbacks (at least, certainly not for add_filter()) the short answer is "you can't". At least, not in a tidy way.

这里有几个选项,具体取决于您在做什么.第一个是最好的,但您可能无法使用它:

There are a couple of options here, depending on what you are doing. The first is the best, but you may not be able to use it:

编写一个调用函数的包装函数:

function gr_wp_list_pages_excludes_1 ($exclude_array) {
  $custom_arg = 'whatever';
  gr_wp_list_pages_excludes_1($exclude_array, $custom_arg)
}

这仅在您在给定情况下始终传递相同的自定义参数时才有效 - 您将为每种不同的情况编写这些包装函数之一,并将包装函数的名称传递给 add_filter().或者,如果您希望它真正具有动态性,则需要...

This will only work if you are always passing the same custom argument in a given situation - you would write one of these wrapper functions for each different situation, and pass the name of the wrapper function to add_filter(). Alternatively, if you want it to be truly dynamic, you would need to...

使用全局变量:(参考:变量范围, $GLOBALS)

function gr_wp_list_pages_excludes($exclude_array) {
    global $gr_wp_list_pages_excludes_custom_arg;
    $id_array=$array('22');
    $exclude_array=array_merge($id_array, $exclude_array);
    return $exclude_array;
}

使用这种方法意味着您可以通过将任何您喜欢的数据分配给全局范围内的 $gr_wp_list_pages_excludes_custom_arg 来将其传递到函数中.这通常被认为是不好的做法,并且非常不赞成,因为它会产生混乱和不可读的代码,并使内存空间充满额外的变量.请注意,为了避免冲突,我使变量名非常长且特定于函数,这是使用全局变量的另一个问题.虽然这会奏效,但只有在绝对必要时才使用它.

Using this approach means that you can pass any data you like into the function by assigning it to $gr_wp_list_pages_excludes_custom_arg in the global scope. This is generally regarded as bad practice and heavily frowned upon, because it makes for messy and unreadable code and leaves the memory space littered with extra variables. Note that I have made the variable name very long and specific to the function to avoid collisions - another problem with using global variables. While this will work, only use it if you absolutely have to.

这篇关于如何将附加参数传递给 wordpress 过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆