Support » Developing with WordPress » Include callback from another file in plugin on widgets_init hook

  • Resolved Rajarshi Bose


    I am having trouble understanding why I cannot include a callback on the action hook ‘widgets_init’ in my plugin’s index.php from another file using include(‘path’)like I normally do .
    Generally , to keep my index.php file of my plugin clean I include callbacks like below

    include( 'includes/init.php' );
    add_action( 'init', 'recipe_init' );

    But for the ‘widgets_init’ hook I cannot directly include like below :

    include( '/includes/widgets.php' );
    add_action( 'widgets_init', 'r_widgets_init' );

    Which thorws an error :

    Warning: include(/includes/widgets.php): failed to open stream: No such file or 
    directory in C:\xampp\htdocs\clean1\wp-content\plugins\recipe2\index.php on line 29
    Warning: include(): Failed opening '/includes/widgets.php' for inclusion 
    (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\clean1\wp-content\plugins
    \recipe2\index.php on line 2 :

    Instead something like below works :

    include( dirname(RECIPE_PLUGIN_URL) . '/includes/widgets.php' );
    add_action( 'widgets_init', 'r_widgets_init' );

    I checked the functions.php of my theme and there we seem to be able to include a
    callback on the same hook directly :

    include( get_theme_file_path( '/includes/widgets.php' ) );
    add_action( 'widgets_init', 'ju_widgets' );

    I am curious as to why it doesnt work in case of plugins while in the theme it
    works ? I checked and found ‘widgets_init’ hook to be trigerred pretty late
    after ‘plugins_loaded’ hook is fired so all my plugin code should be available by
    the time ‘widgets_init’ is fired or am I misunderstanding how WP loads ?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz


    I’d advise against using relative paths for anything WP related. Your code will be more robust and reliable when you use full absolute paths built from functions like plugin_dir_path().

Viewing 1 replies (of 1 total)
  • The topic ‘Include callback from another file in plugin on widgets_init hook’ is closed to new replies.