一种方法(可能是邪恶的)是通过使用tr
字段$form_fields
:
function set_image_data( $form_fields, $post ) {
$form_fields[\'text_color\'] = array(
\'label\' => \'Text Color\',
\'input\' => \'text\',
\'value\' => get_post_meta( $post->ID, \'_text_color\', true )
);
ob_start();
?>
<script type="text/javascript">
jQuery(\'[name$="[text_color]"]\').myColorPicker();
</script>
<?php
$text_color_js = ob_get_clean();
$form_fields[\'text_color_js\'] = array(
\'tr\' => $text_color_js, // Adds free-form stuff to table.
);
return $form_fields;
}
add_filter( \'attachment_fields_to_edit\', \'set_image_data\', 10, 2 );
javascript使用的是
wpColorPicker
将覆盖
close
触发
change
事件(隐藏后需要
text_color
字段从未获得/失去焦点,因此不会自行完成):
add_action( \'admin_print_footer_scripts\', function () {
?>
<script type="text/javascript">
jQuery(function ($) {
// Extend wpColorPicker to trigger change on close.
$.widget(\'custom.myColorPicker\', $.wp.wpColorPicker, {
close: function () {
this._super();
if (this.initialValue !== this.element.val()) {
this.element.change();
}
}
});
});
</script>
<?php
}, 50 );
您可以选择将上述内容包装成一个条件,以便它只包含上载时的脚本,但在某些情况下可能不会触发。
if ( get_current_screen()->base == \'upload\' ) {}
然后是要加载的标准内容
wp-color-picker
并保存数据:
add_action( \'admin_enqueue_scripts\', function () {
if ( get_current_screen()->base == \'upload\' ) {
wp_enqueue_style( \'wp-color-picker\' );
wp_enqueue_script( \'wp-color-picker\' );
}
});
add_filter( \'attachment_fields_to_save\', function ( $post, $attachment ) {
if ( isset( $attachment[\'text_color\'] ) ) {
update_post_meta( $post[\'ID\'], \'_text_color\', $attachment[\'text_color\'] );
}
return $post;
}, 10, 2 );
Update
这种用法在
wpColorPicker
(见trac
https://core.trac.wordpress.org/ticket/32856) 在这种情况下,如果颜色选择器保持打开状态,并且附件详细信息模式关闭,则会引发一个异常,从而使事情进入有趣的状态。解决方法是不要调用
this._super();
在(非常方便地重写)结束时,但要复制代码,请执行以下修复:
add_action( \'admin_print_footer_scripts\', function () {
?>
<script type="text/javascript">
jQuery(function ($) {
// Extend wpColorPicker to trigger change on close.
$.widget(\'custom.myColorPicker\', $.wp.wpColorPicker, {
close: function () {
this.element.hide();
if ( this.element.iris( \'instance\' ) ) {
this.element.iris( \'toggle\' );
}
this.button.addClass( \'hidden\' );
this.toggler.removeClass( \'wp-picker-open\' );
$( \'body\' ).off( \'click.wpcolorpicker\', this.close );
if (this.initialValue !== this.element.val()) {
this.element.change();
}
}
});
});
</script>
<?php
}, 50 );