• Resolved Guido

    (@guido07111975)


    Hi,

    I’m trying to let users of my plugin override plugin template via their (child) theme, by using this tutorial.

    It works, but not when adding my own plugin template file.
    My file contains many variables and I’m only getting the undefined variable notifications:

    
    Notice: Undefined variable: output in in C:\wamp\www\my-domain\wp-content\plugins\my-plugin-slug\my-template-file.php on line 8
    Notice: Undefined variable: page_meta_section_start in C:\wamp\www\my-domain\wp-content\plugins\my-plugin-slug\my-template-file.php on line 10
    ETC ETC
    

    I have no idea why this happens, every variable is initialised within my plugin.
    Even without overriding this file (so when it uses native plugin file) I encounter this.
    I include file similar to how mentioned in tutorial:

    
    $output .= wcpt_get_template( 'my-template-file.php' );
    

    Any ideas?

    Guido

Viewing 3 replies - 1 through 3 (of 3 total)
  • That wcpt_get_template function does not return a value. It only includes the template, which means that the code runs in the context of the function, where your variables are not defined. It’s not a good way to do things that need global variables.

    Moderator bcworkz

    (@bcworkz)

    Hi Guido,

    As you likely know, variables would stay in scope if you were to simply include another file which uses variables already assigned outside of the included file, assuming the variables are in scope with the include statement. As soon as you offload the include statement to a function, the variables external to the function become out of scope. As Joy implies, you could keep the variables in scope by declaring them global. A generally frowned upon technique, even though WP makes extensive use of them. Heavy reliance on globals is an indication of a poorly thought out project.

    When a function is not setup to pass the desired variables, you don’t have many options other than globals. You could build a class to contain static properties which would stay in scope, but doing so isn’t really a lot different than using globals. The class just allows us to say “hey, I never use globals!” ??

    If the function returned the needed file reference instead of including it itself, then you could directly include the file from where your variables are still in scope.

    Thread Starter Guido

    (@guido07111975)

    Hi Joy and BC,

    Aha, I now fully understand it. Did not realize the include is actually part of a function that’s outside the “scope”. So I should take another look at the structure of the template file of my plugin..

    Thanks!

    Guido

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Plugin template override with undefined variable’ is closed to new replies.