函数文档

image_align_input_fields()

💡 云策文档标注

概述

image_align_input_fields() 函数用于生成图像对齐选项的 HTML 单选按钮组,并支持指定默认选中项。它基于用户设置或传入参数确定对齐方式,并输出安全的 HTML 代码。

关键要点

  • 函数接受两个参数:$post(WP_Post 对象,必需)和 $checked(字符串,可选,默认为空)。
  • 如果 $checked 为空,函数会调用 get_user_setting('align', 'none') 获取用户默认对齐设置。
  • 定义了对齐选项数组,包括 'none'、'left'、'center'、'right' 及其翻译标签。
  • 检查 $checked 是否在有效对齐选项中,否则默认为 'none'。
  • 使用 esc_attr() 转义属性值,确保 HTML 安全性。
  • 返回包含单选按钮的 HTML 字符串,每个按钮对应一个对齐选项。

代码示例

function image_align_input_fields( $post, $checked = '' ) {
    if ( empty( $checked ) ) {
        $checked = get_user_setting( 'align', 'none' );
    }

    $alignments = array(
        'none'   => __( 'None' ),
        'left'   => __( 'Left' ),
        'center' => __( 'Center' ),
        'right'  => __( 'Right' ),
    );

    if ( ! array_key_exists( (string) $checked, $alignments ) ) {
        $checked = 'none';
    }

    $output = array();

    foreach ( $alignments as $name => $label ) {
        $name     = esc_attr( $name );
        $output[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'" .
            ( $checked === $name ? " checked='checked'" : '' ) .
            " /> <label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
    }

    return implode( "n", $output );
}

注意事项

  • 函数依赖于 get_user_setting() 获取用户设置,确保用户界面一致性。
  • 使用 __() 进行国际化翻译,支持多语言环境。
  • 输出 HTML 时使用 esc_attr() 转义,防止 XSS 攻击。
  • 该函数自 WordPress 2.7.0 版本引入,主要用于 get_attachment_fields_to_edit() 中生成附件编辑表单字段。

📄 原文内容

Retrieves HTML for the image alignment radio buttons with the specified one checked.

Parameters

$postWP_Postrequired
$checkedstringrequired

Return

string

Source

function image_align_input_fields( $post, $checked = '' ) {

	if ( empty( $checked ) ) {
		$checked = get_user_setting( 'align', 'none' );
	}

	$alignments = array(
		'none'   => __( 'None' ),
		'left'   => __( 'Left' ),
		'center' => __( 'Center' ),
		'right'  => __( 'Right' ),
	);

	if ( ! array_key_exists( (string) $checked, $alignments ) ) {
		$checked = 'none';
	}

	$output = array();

	foreach ( $alignments as $name => $label ) {
		$name     = esc_attr( $name );
		$output[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'" .
			( $checked === $name ? " checked='checked'" : '' ) .
			" /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
	}

	return implode( "n", $output );
}

Changelog

Version Description
2.7.0 Introduced.