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


How to pass a value of variable to a function in PHP (wordpress)

好的,我有这样的代码:

//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),所以我可以在strtotime("-$period days")中使用它?

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

谢谢。

可以使用global关键字从全局命名空间导入变量。更多阅读请点击:http://php.net/manual/en/language.variables.scope.php

//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' );
编辑:我从你的函数的声明中删除了$period变量