WordPress插件开发教程:trailingslashit

Author: 陌小雨Date: 2019-04-05View: 377

1、trailingslashit
在字符串末尾添加 /
添加之前会删除字符串末尾已有的 /,这样可以防止添加两个 /

'DWQA_TEMP_DIR' => trailingslashit( get_template_directory() ),
'DWQA_TEMP_URL' => trailingslashit( get_template_directory_uri() ),
'DWQA_STYLESHEET_DIR' => trailingslashit( get_stylesheet_directory() ),
'DWQA_STYLESHEET_URL' => trailingslashit( get_stylesheet_directory_uri() ),

2、plugin_dir_url
返回当前插件的目录 URI,例如
echo plugin_dir_url(__FILE__ );
//输出:https://dedewp.com/wp-content/plugins/myplugin/

注意结尾有反斜杠。
3、plugin_dir_path()
返回当前插件目录的服务器绝对路径,例如
echo plugin_dir_path(__FILE__ );
//输出:/home/user/public_html/wp-content/plugins/myplugin/

可以用来引用文件,例如

<?php
define('MYPLUGINNAME_PATH', plugin_dir_path(__FILE__) );
require MYPLUGINNAME_PATH . 'includes/class-metabox.php';
require MYPLUGINNAME_PATH . 'includes/class-widget.php';
?>

例子:

public function define_constants() {
	$defines = array(
		'DWQA_DIR' => plugin_dir_path( __FILE__ ),
		'DWQA_URI' => plugin_dir_url( __FILE__ ),
		'DWQA_TEMP_DIR' => trailingslashit( get_template_directory() ),
		'DWQA_TEMP_URL' => trailingslashit( get_template_directory_uri() ),
		'DWQA_STYLESHEET_DIR' => trailingslashit( get_stylesheet_directory() ),
		'DWQA_STYLESHEET_URL' => trailingslashit( get_stylesheet_directory_uri() ),
		);

	foreach( $defines as $k => $v ) {
			if ( !defined( $k ) ) {
				define( $k, $v );
			}
		}
	}