找到了一个很好的教程来做这件事:http://javatechig.com/wordpress/how-to-implement-color-picker-with-wordpress
<?php
// add the meta box
function wdm_add_meta_box() {
add_meta_box(\'wdm_sectionid\', \'Post Background\', \'wdm_meta_box_callback\', \'post\');
}
add_action( \'add_meta_boxes\', \'wdm_add_meta_box\' );
// callback function that renders your meta-box on the admin pages
function wdm_meta_box_callback( $post ) {
wp_nonce_field( \'wdm_meta_box\', \'wdm_meta_box_nonce\' );
$color = get_post_meta( $post->ID, \'post_bg\', true );
?>
<div class="custom_meta_box">
<p>
<input class="color-field" type="text" name="post_bg" value="<?php echo \'#\'.$color; ?>"/>
</p>
<div class="clear"></div>
</div>
<script>
// Add WordPress\'s custom color picker to all inputs that have \'color-field\' class
(function( $ ) {
$(function() {
$(\'.color-field\').wpColorPicker();
});
})( jQuery );
</script>
<?php
}
// save the user\'s meta-box input to the database
function wdm_save_meta_box_data( $post_id ) {
if ( !isset( $_POST[\'wdm_meta_box_nonce\'] ) ) {
return;
}
if ( !wp_verify_nonce( $_POST[\'wdm_meta_box_nonce\'], \'wdm_meta_box\' ) ) {
return;
}
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) {
return;
}
if ( !current_user_can( \'edit_post\', $post_id ) ) {
return;
}
$post_bg = ( isset( $_POST[\'post_bg\'] ) ? sanitize_html_class( $_POST[\'post_bg\'] ) : \'\' );
update_post_meta( $post_id, \'post_bg\', $post_bg );
}
add_action( \'save_post\', \'wdm_save_meta_box_data\' );
// enables use of wordpress\'s custom color picker
function wpse_80236_Colorpicker(){
wp_enqueue_style( \'wp-color-picker\');
//
wp_enqueue_script( \'wp-color-picker\');
}
add_action(\'admin_enqueue_scripts\', \'wpse_80236_Colorpicker\');
?>
如果需要获取颜色代码ID,只需在函数中添加以下代码行即可。php文件。
$post_background = get_post_meta( get_the_ID(), \'post_bg\', true );
echo $post_background // here is your color code
如果希望此操作适用于页面而不是帖子,请替换
post
具有
page
在
wdm_add_meta_box()
作用