0

Currently I am coding in my own custom plugin. For some reason I can't use conditional tags inside my function. For example

 function check_home() {
    if(is_home()) {
       $my_val=1;
    } else {
     $my_val=2;
    }
    return $my_val;
  }

It's returning following error

Fatal error: Uncaught Error: Call to undefined function is_home()

I checked and I found a solution & it is working fine.

It saying to add this add_action('wp', 'check_home');

But now I want to get the value of function to variable. But it is showing error.

 add_action('wp', 'check_home');
 function check_home() {
    if(is_home()) {
       $my_val=1;
    } else {
     $my_val=2;
    }
    return $my_val;
  }
  
  $my_ver = check_home();
  echo $my_ver;

Then it showing following error.

Fatal error: Uncaught Error: Call to undefined function is_home()

Now how can i solve this error ? What i am missing ?

1 Answer 1

1

It's a timing issue. This tries to call is_home() before that function exists.

$my_ver = check_home();   

It works in the function called by add_action because then is_home() does exist because WP has fully loaded.

If you load php files in your plugin, then you can call check_home anytime in those files.

For example:

define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
function ab_load_files() {
   require( MY_PLUGIN_PATH . '/ab-functions.php' );
}    
add_action( 'init', 'ab_load_files' );

Then this code will work if placed in ab-functions.php

$my_ver = check_home();
echo $my_ver;
1
  • Thank you . This seems to be more reasonable. I will try this. I wonder from where you are getting these informations. Commented Dec 5, 2021 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.