我有两个WordPress函数:
$wpb_set_post_views = function($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
};
add_action( 'wp_head', function ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
$wpb_set_post_views($post_id);
});
但是页面返回最后一行的Notice: Undefined variable: wpb_set_post_views
在PHP中处理闭包时,您需要确保将任何超出范围的变量放入闭包范围。这与JavaScript不同,闭包可以访问PHP作用域中声明的变量。
你的匿名函数应该如下所示
function() use ($variableNeeded) { }
你就可以访问这个变量了。
重要的是要记住,这是一个按值传递的场景,所以对该变量的任何更改都不会在闭包之外反映出来,所以您需要按引用传递来进行更改。
function() use (&$variableNeeded) { }
使用global关键字访问函数中的外部变量。
所以你的代码将是add_action( 'wp_head', function ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
global $wpb_set_post_views;
$wpb_set_post_views($post_id);
});
或
add_action( 'wp_head', function ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
$wpb_set_post_views = $GLOBALS['wpb_set_post_views'];
$wpb_set_post_views($post_id);
});
请参考http://php.net/manual/en/language.variables.scope.php