image_link_input_fields()
云策文档标注
概述
image_link_input_fields() 函数用于生成附件链接 URL 按钮的 HTML 代码,支持指定默认链接类型。它基于附件 ID 和 URL 类型参数,返回包含单选按钮和 URL 输入框的 HTML 字符串。
关键要点
- 函数接受两个参数:$post(WP_Post 对象,必需)和 $url_type(字符串,可选,默认为空)。
- 返回值为字符串,包含 HTML 代码,用于在编辑界面中显示链接选项。
- 函数内部使用 wp_get_attachment_url() 获取附件文件 URL,get_attachment_link() 获取附件文章链接。
- 如果 $url_type 为空,则通过 get_user_setting() 获取用户设置的默认链接类型。
- 支持 'file' 和 'post' 两种链接类型,分别对应文件 URL 和附件文章 URL。
- 输出包括单选按钮选项(None、File URL、Attachment Post URL)和一个 URL 输入框。
代码示例
function image_link_input_fields( $post, $url_type = '' ) {
$file = wp_get_attachment_url( $post->ID );
$link = get_attachment_link( $post->ID );
if ( empty( $url_type ) ) {
$url_type = get_user_setting( 'urlbutton', 'post' );
}
$url = '';
if ( 'file' === $url_type ) {
$url = $file;
} elseif ( 'post' === $url_type ) {
$url = $link;
}
return "
ID][url]' value='" . esc_attr( $url ) . "' />
" . __( 'None' ) . "
" . __( 'File URL' ) . "
" . __( 'Attachment Post URL' ) . '
';
}注意事项
- 函数依赖于 WordPress 核心函数如 wp_get_attachment_url() 和 get_attachment_link(),确保附件存在且可访问。
- URL 输出使用 esc_attr() 和 esc_url() 进行转义,以提高安全性。
- 文本使用 __() 函数进行国际化处理,支持多语言翻译。
- 该函数自 WordPress 2.7.0 版本引入,主要用于 get_attachment_fields_to_edit() 中生成编辑字段。
原文内容
Retrieves HTML for the Link URL buttons with the default link type as specified.
Parameters
$postWP_Postrequired$url_typestringrequired
Source
function image_link_input_fields( $post, $url_type = '' ) {
$file = wp_get_attachment_url( $post->ID );
$link = get_attachment_link( $post->ID );
if ( empty( $url_type ) ) {
$url_type = get_user_setting( 'urlbutton', 'post' );
}
$url = '';
if ( 'file' === $url_type ) {
$url = $file;
} elseif ( 'post' === $url_type ) {
$url = $link;
}
return "
<input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr( $url ) . "' /><br />
<button type='button' class='button urlnone' data-link-url=''>" . __( 'None' ) . "</button>
<button type='button' class='button urlfile' data-link-url='" . esc_url( $file ) . "'>" . __( 'File URL' ) . "</button>
<button type='button' class='button urlpost' data-link-url='" . esc_url( $link ) . "'>" . __( 'Attachment Post URL' ) . '</button>
';
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |