个性化阅读
专注于IT技术分析

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

我正在编写一些用于wordpress主题开发的代码, 我打算将其重用于将来的主题(甚至可以上传到github)。它由几十个文件以及一些javascript和css文件组成。

我将来唯一要做的承诺是, 我所有的文件都将放置在同一目录中, 该目录放置在主题目录中的位置是未知的。

如果我不知道文件的绝对路径(get_template_directory_uri。

我也希望与其编写十几行的include \ require, 不如编写一个包含文件, 该文件将通过它们的相对路径包含其余文件。


#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"/>

希望有人觉得这有用。


#2


有两个主要的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);

你还可以查看一个非常有用的WP函数get_template_part(), 它可能会改变你对解决方案的想法。


#3


你可以从WP函数下面检索主题目录URI, 然后可以将文件名与相应的文件夹名一起传递。

get_template_directory_uri()

#4


我最终使用目录名(__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中编辑代码。

赞(0)
未经允许不得转载:srcmini » 在WordPress主题开发中使用相对路径的正确方法是什么?

评论 抢沙发

评论前必须登录!