3

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.

marcelo2605
  • 2,734
  • 4
  • 29
  • 55

2 Answers2

10

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) { }
Zarathuztra
  • 3,215
  • 1
  • 20
  • 34
  • There's really no need to pass it in by reference. – Andrei Sep 07 '15 at 14:57
  • 2
    In this example, maybe not, but if you need the value change to be reflected outside the closure, you need to pass by reference. Calling closures is the same as calling any other function, so you will pass by value. – Zarathuztra Sep 07 '15 at 14:58
0

Use global keyword to access the outside variables in a function.

So your code will be

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);
});

Or

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);
    });

Please refer http://php.net/manual/en/language.variables.scope.php

user3535945
  • 241
  • 1
  • 10