use multiple files in wordpress plugin - Call to u

2019-04-09 06:16发布

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 includes 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 i'm doing wrong ?

thanks

3条回答
不美不萌又怎样
2楼-- · 2019-04-09 06:43

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';
?>
查看更多
走好不送
3楼-- · 2019-04-09 07:00

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()

查看更多
贪生不怕死
4楼-- · 2019-04-09 07:09

Use plugin_dir_path( __FILE__ ); to get files of your plugin. Use code reference below:

$dir = plugin_dir_path( __FILE__ );

require_once($dir.'1.php');

require_once($dir.'2.php');

require_once($dir.'3.php');

require_once($dir.'4.php');
查看更多
登录 后发表回答