0

I am getting trouble including the seperate PHP file in callback function.

add_menu_page('Keyword Analyzer', 'Keyword Analyzer', 'manage_options', 
              'keyword_analyzer_menu', 'Key_Analyzer_Groups::init');

My Key_Analyzer_Groups class has the following codes:

class Key_Analyzer_Groups {



    public static function init() {

        include_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/templates/groups.php';
    }
}

but if i directly include the html on the init() function then output works as expected but not with the included file.

I am sure there should be some trick to seperate the view templates. Please guide me to the right direction.

Folder Structure:

plugin
- admin
  - views
   - key-analyzer-groups.php ( Key_Analyzer_Groups CLASS )
  - templates
   - groups.php ( Holds HTML Parts )
9
  • is it namespaced? – ngearing Apr 19 '18 at 6:27
  • @Nath no it is not. – jogesh_pi Apr 19 '18 at 6:29
  • Does array('Key_Analyzer_Groups', 'init') work? – kero Apr 19 '18 at 7:10
  • @kero i used static method public static function init, thats why i used Key_Analyzer_Groups::init on callback. – jogesh_pi Apr 19 '18 at 7:19
  • i tried with array('Key_Analyzer_Groups', 'init') its not working. – jogesh_pi Apr 19 '18 at 7:23
3

Your problem is with the path you're using to include the file.

plugin_dir_path() just gets the directory of the given file/directory with a trailing slash. So if your code is here:

plugin/admin/views/key-analyzer-groups.php

Then dirname( __FILE__ ) will return

plugin/admin/views

So plugin_dir_path( dirname( __FILE__ ) ) will return

plugin/admin/

Which means that you are trying to include this path:

plugin/admin/admin/templates/groups.php

Which doesn't exist.

If you want a reliable way to get the directory for your plugin to use throughout your code, then what you should do is define a function in your root plugin file that returns the path, then use that function throughout your code:

function key_analyzer_plugin_path() {
    return plugin_dir_path( __FILE__ );
}

Then use that function in your other files to include:

class Key_Analyzer_Groups {
    public static function init() {
        include_once key_analyzer_plugin_path() . 'admin/templates/groups.php';
    }
}

You could also tweak this approach to create a function for including files inside your plugin:

function key_analyzer_include( $file ) {
    $file = ltrim( $file, '/' );

    include plugin_dir_path( __FILE__ ) . $file;
}

Now you can use that function to include all your files by passing it a path relative to the main plugin file:

class Key_Analyzer_Groups {
    public static function init() {
        key_analyzer_include( 'admin/templates/groups.php' );
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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