函数文档

trailingslashit()

💡 云策文档标注

概述

trailingslashit() 是 WordPress 核心函数,用于在字符串末尾添加一个正斜杠,主要用于路径处理。它会先移除现有的尾部斜杠,再添加一个正斜杠,避免重复斜杠问题。

关键要点

  • 函数功能:向字符串添加尾部正斜杠,并自动处理现有斜杠以防止重复
  • 主要用途:适用于路径处理,但也可用于其他字符串场景
  • 参数:接受一个必需字符串参数 $value,返回添加斜杠后的字符串
  • 内部实现:基于 untrailingslashit() 函数构建,确保简洁高效

代码示例

// 基本用法示例
$path = trailingslashit( '/home/julien/bin/dotfiles' );
// $path 现在为: /home/julien/bin/dotfiles/

// 在 WordPress 开发中的实际应用
wp_enqueue_style( 'main-css', trailingslashit( get_template_directory_uri() ) . 'style.css' );
require trailingslashit( get_template_directory() ) . 'inc/custom-theme-functions.php';

注意事项

  • 该函数不提供特定路径支持,开发者需确保输入值适合路径使用
  • 与 untrailingslashit() 函数配合使用,可灵活处理路径斜杠问题
  • 在 WordPress 核心和插件/主题开发中广泛使用,涉及文件系统、URL 生成等多个场景

📄 原文内容

Appends a trailing slash.

Description

Will remove trailing forward and backslashes if it exists already before adding a trailing forward slash. This prevents double slashing a string or path.

The primary use of this is for paths and thus should be used for paths. It is not restricted to paths and offers no specific path support.

Parameters

$valuestringrequired
Value to which trailing slash will be added.

Return

string String with trailing slash added.

Source

function trailingslashit( $value ) {
	return untrailingslashit( $value ) . '/';
}

Changelog

Version Description
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Two examples that you could use the trailingslashit() function for:
    To enqueue a style.css file

    wp_enqueue_style( 'main-css', trailingslashit( get_template_directory_uri() ) . 'style.css' );

    To include a php file using the require statement

    require trailingslashit( get_template_directory() ) . 'inc/custom-theme-functions.php';