在wordpress主题开发中使用相对路径的正确方法是什么?

时间:2017-04-19 17:55:44

标签: php wordpress wordpress-theming

我正在为wordpress主题开发编写一些代码,我计划重用未来的主题(甚至可以上传到github)。 它包含几十个文件和一些javascript和css文件。

我愿意为将来做出的唯一承诺是我的所有文件都将放在同一目录中,这个目录放在主题目录中的位置是未知的。

如果我不知道文件的绝对路径(get_template_directory_uri。''),我应该如何将文件排入队列(wp_enqueue_style,wp_enqueue_script函数)?

我也希望不是包含十几行include \ require,而是可以编写一个包含其文件的包含文件。

4 个答案:

答案 0 :(得分:1)

如果您需要主题索引文件中的路径,那么一个简单的解决方案(不一定是最合适的方式)可能是这样的:

 <?php
        $TEMPLATE_PATH = get_template_directory_uri(); 
        $TEMPLATE_PATH = parse_url($TEMPLATE_PATH, PHP_URL_PATH);
      ?>

然后您可以使用$ TEMPLATE_PATH作为相对路径,如下所示:

<link href="<?php echo $TEMPLATE_PATH; ?>/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

这将输出如下:

<link href="/wp-content/themes/ThemesName/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

希望有人觉得这很有用。

答案 1 :(得分:0)

有两个主要的WP函数可用于查找主题中的相对路径:

get_template_directory()

get_template_directory_uri()

您可以创建一个名为“可重复使用”的主题子目录。或者适当的东西,这是一个顶级子目录。此外,让我们说你的文件集如下:

mytheme/reusable/loader.php
mytheme/reusable/include-me.php
mytheme/reusable/include-another.php
mytheme/reusable/js/reuse.js
mytheme/reusable/css/reuse.css

loader.php:

<?php
// add as many files as you want to this array
$include_paths = array(
    'reusable/include-me.php',
    'reusable/include-another.php',
);
// loop through the paths and include them if they exist
$template_directory = trailingslashit(get_template_directory());
foreach( $include_paths as $path ) {
    $complete_path = $template_directory . $path;
    if( file_exists( $complete_path ) ) {
        include($complete_path);
    }
}
// function to enqueue js and css
function reusable_enqueue_scripts() {
    $template_directory_uri = get_template_directory_uri();
    wp_enqueue_style( 'reusable-style', $template_directory_uri . '/css/reuse.css');
    wp_enqueue_script( 'reusable-js', $template_directory_uri . '/js/reuse.js');
}
// add function to enqueue action hook
add_action( 'wp_enqueue_scripts', 'reusable_enqueue_scripts' );

然后在你主题的functions.php文件中:

$reusable = trailingslashit(get_template_directory()).'reusable/loader.php';
include($reusable);

还有一个名为get_template_part()的非常有用的WP功能,您look into可能会改变您对解决方案的看法。

答案 2 :(得分:0)

您可以从WP功能下面检索主题目录URI,然后您可以传递具有相应文件夹名称的文件名。

get_template_directory_uri()

答案 3 :(得分:0)

我最终使用dirname(__FILE__)来确定loader.php的位置, 并从中减去get_template_directory()以获取我的代码在主题目录中的相对路径,如下所示: $MY_PATH = str_replace(realpath(get_template_directory()),"",dirname(__FILE__)));

最终结果load.php:

$MY_PATH =  str_replace(realpath(get_template_directory()),"",dirname(__FILE__)));

require_once('file1.php');
require_once('file2.php');
require_once('file3.php');

function my_scripts() {
    $mypath = $GLOBALS['MY_PATH'];
    wp_enqueue_style( 'my-style', $template_directory_uri . $mypath . '/style.css');
    wp_enqueue_script( 'my-js', $template_directory_uri . $mypath . '/script.js');
}

add_action( 'wp_enqueue_scripts', 'my_scripts' );

现在我可以在不编辑loader.php中的代码的情况下更改我的代码目录位置。