函数文档

wp_slash()

💡 云策文档标注

概述

wp_slash() 函数用于为字符串或数组中的字符串递归添加反斜杠,主要用于准备需要转义数据的核心 API 调用。它不应直接用于 SQL 查询转义。

关键要点

  • 功能:为字符串或数组递归添加反斜杠,处理单引号、双引号、反斜杠和 NUL 字符
  • 适用场景:准备数据供 WordPress 核心 API 使用,如 wp_insert_post()、wp_update_post() 等
  • 注意事项:不应用于 SQL 查询转义,应使用 $wpdb->prepare() 或 esc_sql()
  • 参数:接受字符串或数组,返回相同类型的转义后值
  • 版本变化:自 5.5.0 起,非字符串值(如整数、布尔值)保持不变

代码示例

// 字符串使用示例
function wpdocs_toolset_string_add_slashes() {
    $name = __( "O'Reilly & Associates", 'textdomain' );
    $name = wp_slash( $name );
    echo "name={$name}";
}
add_action( 'pre_get_posts', 'wpdocs_toolset_string_add_slashes' );

// 数组使用示例
function wpdocs_toolset_array_add_slashes() {
    $names = array( __( "Baba O'Reilly", 'textdomain' ), __( 'class of '99', 'textdomain' ) );
    $names = wp_slash( $names );
    print_r( $names );
}
add_action( 'pre_get_posts', 'wpdocs_toolset_array_add_slashes' );

📄 原文内容

Adds slashes to a string or recursively adds slashes to strings within an array.

Description

This should be used when preparing data for core API that expects slashed data.
This should not be used to escape data going directly into an SQL query.

Parameters

$valuestring|arrayrequired
String or array of data to slash.

Return

string|array Slashed $value, in the same type as supplied.

Source

function wp_slash( $value ) {
	if ( is_array( $value ) ) {
		return array_map( 'wp_slash', $value );
	}

	if ( is_string( $value ) ) {
		return addslashes( $value );
	}

	return $value;
}

Changelog

Version Description
5.5.0 Non-string values are left untouched.
3.6.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Usage with an array

    How to use wp_slash with an array within your plugin.

    function wpdocs_toolset_array_add_slashes() {
        $names = array( __( "Baba O'Reilly", 'textdomain' ), __( 'class of '99', 'textdomain' ) );
        $names = wp_slash( $names );
        print_r( $names );
    }
    add_action( 'pre_get_posts', 'wpdocs_toolset_array_add_slashes' );