Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use multiple files in a WordPress plugin - Call to undefined function add_action()

Tags:

php

wordpress

I'm trying to write a plugin with multi files. I'm sure I did it before without a problem, but now I have the problem in the subject.

In the main plugin file I included a file name - ydp-includes.php. Inside of ydp-includes.php I included all the files I wanted like this:

<?php
    include(dirname(__FILE__) . '/1.php');
    include(dirname(__FILE__) . '/2.php');
    include(dirname(__FILE__) . '/3.php');
    include(dirname(__FILE__) . '/4.php');
?>

But I'm getting:

Fatal error: Call to undefined function add_action()

The files are included, but for a reason I can't see at the moment WordPress doesn't see them as one plugin package and each WordPress function inside ignored.

Is there another best practice way to develop multiple files WordPress plugin? What am I doing wrong?

like image 483
user1818018 Avatar asked Nov 12 '12 12:11

user1818018


2 Answers

In PHP include is a statement, not a function.

So it should be:

<?php
include dirname( __FILE__ ) .'/1.php';
include dirname( __FILE__ ) .'/2.php';
include dirname( __FILE__ ) .'/3.php';
include dirname( __FILE__ ) .'/4.php';
?>

Or to be perfect:

<?php
require_once dirname( __FILE__ ) .'/1.php';
require_once dirname( __FILE__ ) .'/2.php';
require_once dirname( __FILE__ ) .'/3.php';
require_once dirname( __FILE__ ) .'/4.php';
?>
like image 195
Sudar Avatar answered Sep 25 '22 13:09

Sudar


Based on the error message, it sounds like you're trying to access the plugin file directly, which is incorrect. WordPress uses a front-controller design pattern, which means that you're going to want to have your files like this:

my-plugin-folder/my-plugin-name.php
my-plugin-folder/includes/ydp-includes.php
my-plugin-folder/includes/ydp-database.php

Inside of the my-plugin-name.php:

//Get the absolute path of the directory that contains the file, with trailing slash.
define('MY_PLUGIN_PATH', plugin_dir_path(__FILE__)); 
//This is important, otherwise we'll get the path of a subdirectory
require_once MY_PLUGIN_PATH . 'includes/ydb-includes.php';
require_once MY_PLUGIN_PATH . 'includes/ydb-database.php';
//Now it's time time hook into the WordPress API ;-)
add_action('admin_menu', function () {
  add_management_page('My plugin Title', 'Menu Title', 'edit_others_posts', 'my_menu_slug', 'my_plugin_menu_page_content'
});
//Php 5.3+ Required for anonymous functions. If using 5.2, create a named function or class method

function my_plugin_menu_page_content () {
    //Page content here
}

That will add a WordPress admin menu item, and load the required files. You'll also be able to require more files inside of the included files now, using the constant MY_PLUGIN_PATH

See also:

add_menu_page plugin_dir_path()

like image 36
Bob Gregor Avatar answered Sep 25 '22 13:09

Bob Gregor