如何在PHP(wordpress)中将变量值传递给函数

如何在PHP(wordpress)中将变量值传递给函数,php,wordpress,function,variables,Php,Wordpress,Function,Variables,好的,我有这个代码: //let's say: $period = 30; if (!function_exists('filter_where')) { function filter_where($period,$where = '') { $where .= " AND post_date > '" . date('Y-m-d', strtotime("-$period days")) . "'"; return $where; } } add_fi

好的,我有这个代码:

//let's say: 
$period = 30;
if (!function_exists('filter_where')) {
    function filter_where($period,$where = '') {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime("-$period days")) . "'";
    return $where;
    }
}
add_filter( 'posts_where', 'filter_where' );
此代码不起作用,因为在filter_where函数中,$period的值不是30。

如何传递$period(30)的值,以便我可以在strotime中使用它(“-$period days”)?

$period的值可以由用户填充,因此它可能会更改为30以外的其他数字


谢谢。您可以使用global关键字从全局命名空间导入变量。更多阅读:


编辑:我从函数的声明中删除了$period变量

否,它不起作用。函数中的$period返回null,而不是30。再次检查,我从函数的参数列表中删除了$period。它不应该在那里。它仍然返回null,而不是30。我把echo(“period2=$period”);在全球美元期之后;声明来检查该值,它返回null。然后,您还做了一些错误的事情。尝试一个新的php文件,只需此代码(当然手动调用函数)啊。。。我发现了问题!当函数位于另一个函数内时,此过滤器将显示。因此,我必须对父函数进行另一个全局$period声明。谢谢!现在可以了!
//let's say: 
$period = 30;
if (!function_exists('filter_where')) {
    function filter_where($where = '') {
    global $period;
    $where .= " AND post_date > '" . date('Y-m-d', strtotime("-$period days")) . "'";
    return $where;
    }
}
add_filter( 'posts_where', 'filter_where' );