Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 47

Local Paths

Оглавление

Local paths reference locations on the server. PHP provides easy methods for determining paths for almost every case needed. However, to be on the safe side, it's best to use WordPress functions where possible. The plugin_dir_path() function provides an easy way to get the filesystem directory path to your plugin.

<?php $path = plugin_dir_path( $file ); ?>

Parameters:

 $file (string, required): The filename in the current directory path

The following example will print the path of the current directory of the file passed in with a trailing slash using PHP's __FILE__ constant:

<?php echo plugin_dir_path( __FILE__ ); ?>

That code should output a path similar to the following:

/public_html/wp-content/plugins/pdev/

Any file can be passed into the function. The resulting path will point to wherever the file lives in your plugin. If passing in __FILE__ from the primary plugin file, it'll be the path to the root of your plugin. If passing it in from a subfolder in your plugin, it will return the path to the subfolder in your plugin.

Assuming you needed to load a file named /src/functions.php from your plugin that houses some custom functions, use the following code:

<?php include plugin_dir_path( __FILE__ ) . '/src/functions.php'; ?>

It is common practice for plugin authors to store this path as a variable or constant in the plugin's primary file for quick access to the plugin's root folder path, as shown in the following example code:

<?php define( 'PDEV_DIR', plugin_dir_path( __FILE__ ) ); ?>

This allows you to reference PDEV_DIR any time you need it from anywhere in the plugin without having to think about file paths.

Professional WordPress Plugin Development

Подняться наверх