I'm having these two WordPress functions:
$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);
});
But the page return Notice: Undefined variable: wpb_set_post_views
for the last line.
When dealing with Closures in PHP you need to ensure that any out of scope variable is put into the Closure scope. This is unlike JavaScript where closures have access to variables declared in a PHP scope.
Your anonymous function should be as follows
function() use ($variableNeeded) { }
You will then have access to that variable.
It is important to keep in mind that this is a pass by value scenario, so any changes to that variable will not be reflected outside the closure, so you would need to pass by reference to make changes.
function() use (&$variableNeeded) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With