0

I am trying something basic but I can't seem to figure it out or I am not even sure if it is possible to be done in a child theme.

What is am trying is to organize the the codes in the functions.php file in the child theme by creating a separate directory for include files and have all the files in there.

Basically, here is the code in my functions.php file:

require_once( get_stylesheet_directory_uri() . '/inc/myfile.php');

And then myfile.php got this code:

function myfunction( $src ) {

}
add_filter( 'script_loader_src', 'myfunction');

But then I get this error:

PHP Fatal error:  Call to undefined function add_filter()

So now I am wondering if there is a way for me to do what I am trying to achieve in a child theme. I have tried this approach in a parent theme and it seemed to work fine.

Thanks in advance for explanation and suggestions.

1 Answer 1

1

What you're trying to do is possible.

When including php files, use get_stylesheet_directory() in child themes and get_template_directory() in parent themes.

E.g. require_once( get_stylesheet_directory() . '/inc/myfile.php');

get_stylesheet_directory_uri() and get_template_directory_uri() will return URLs. Those functions are useful when enqueuing public assets such as stylesheets and JavaScript.

Also, setting allow_url_include to Off in your php.ini will provide better error reporting in these situations (source).

4
  • Yes, what you suggested is what I have in my code, see codes in the post above. My problem is that in my file.php inside the inc directory, when I use the add_filter code, it throws the error that add_filter is an undefined function.
    – Atasha
    Commented Sep 4, 2016 at 13:30
  • No, our code is not the same! Mine works :) Take a closer look please. You are using get_stylesheet_directory_uri() and I'm using get_stylesheet_directory(). Those are two different functions. Here's a great supplement to the Codex on loading files within WordPress. Commented Sep 4, 2016 at 14:54
  • Sorry, I missed that. Thanks a lot! My code works now. Thanks for the reference links as well. They helped a lot! :)
    – Atasha
    Commented Sep 4, 2016 at 17:07
  • No worries! Glad it's working now. Commented Sep 4, 2016 at 17:13

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.