Skip to content
Advertisement

I keep getting a “Call to undefined function..” error displaying

I am new to PHP programming and I am trying to teach myself WordPress theme development for fun and I am using PhpStorm as my IDE.

I am trying to better understand the inner-workings of WordPress and I am running into a roadblock on something.

I have a sandbox plugin that I created to use to play around with WordPress.

In my “wp-content/plugins/sandbox/sandbox.php” file, I am just running basic PHP code to help me get used to the language as it relates to WordPress.

Also, I installed both Kint and Whoops using Composer to help with debugging.

Now that I got that out of the way, here is what I am doing:

Code #1

namespace MyDevPlaygroundSandbox;

add_action( 'loop_start', __NAMESPACE__ . 'process_the_string' );
function process_the_string() {

    $current_user = wp_get_current_user();

    $data_packet = array(
        'id'    => $current_user->ID,
        'email' => $current_user->user_email,
        'name'  => array(
            'first_name' => $current_user->user_firstname,
            'last_name'  => $current_user->user_lastname,
        ),
    );

    render_user_message( $data_packet );
}

function render_user_message( array $current_user ) {

    $user_id = $current_user['id'];

    d( "Welcome {$current_user['name']['first_name']}, your user id is { {$user_id} }." );

    ddd( "Welcome {$current_user['name']['first_name']}, your user id is {$user_id}." );
}

When I run Code #1 above everything is fine and Kint displays the values just fine.

Now for the problem I am having that I don’t understand about WordPress:

Code #2

namespace MyDevPlaygroundSandbox;

add_action( 'loop_start', __NAMESPACE__ . 'check_logged_in_user' );
function check_logged_in_user(){
    $current_user = wp_get_current_user();
    if ( 0 == $current_user->ID ) {
        d('Not logged in');
    } else {
        ddd('Logged in');
    }
}

check_logged_in_user();

When I run Code #2 above, Whoops reports the following error:

Call to undefined function MyDevPlaygroundSandboxwp_get_current_user

For some reason when I run Code #1, the wp_get_current_user() function loads just fine, but not with Code #2.

Can someone help me understand why this is in laymen’s terms if possible?

What is the difference between Code #1 and Code #2?

How come the wp_get_current_user() function is not loading in Code #2, but it is in Code #1?

Thank you for your help.

Advertisement

Answer

when you use “add_action” command you can not use function name for calling that action, you need to use the call command like this :

do_action("check_logged_in_user");

more information : https://developer.wordpress.org/reference/functions/add_action/

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement