Adding metaboxes to your posts or pages – Color picker metabox

An image displaying a color picker

There are several ways of adding a new feature to your WordPress post or page. There are WordPress Custom Fields, popular plugins like Advanced Custom Fields (ACF), which extend the custom field functionality, and there are WordPress meta boxes.

Notice: This article was written in 2016. WordPress changed a lot since then, so take this article with a grain of salt…

I have grown accustomed to do everything with meta boxes. Whether it’s adding a gallery to a post – if you want a dedicated gallery that is not a part of the post content or maybe in a custom post type (I’ll do a tutorial about that later on), adding a datepicker to your post, or as I’ll describe here add a built in color picker, that you can later use to customize your post or a page.

To start, you need to add a meta box. A meta box is a toolbox that contains various options that will enhance your posts, such as Featured image, Excerpt, Tags etc. In WordPress back end they are placed into two places depending on the context – on the side, or under the post content. You can add them above the content, but that would take some tweaking.

add_action( 'add_meta_boxes', 'mytheme_add_meta_box' );

if ( ! function_exists( 'mytheme_add_meta_box' ) ) {
	function mytheme_add_meta_box(){
		add_meta_box( 'header-page-metabox-options', esc_html__('Header Color', 'mytheme' ), 'mytheme_header_meta_box', 'page', 'side', 'low');
	}
}Code language: JavaScript (javascript)

function_exists() is a useful function if you want to prevent function clashes. This can be avoided though if you use unique enough names. We’ve added our meta box on the side, on pages, and given it the name “Header Color”. You’d change the mytheme with your theme slug of course. The meta box id is header-page-metabox-options and the callback function with which we will add our functionality is called mytheme_header_meta_box.

For our color picker to work we need to enqueue the color picker style and script.

add_action( 'admin_enqueue_scripts', 'mytheme_backend_scripts');

if ( ! function_exists( 'mytheme_backend_scripts' ) ){
	function mytheme_backend_scripts( $hook ) {
		wp_enqueue_style( 'wp-color-picker');
		wp_enqueue_script( 'wp-color-picker');
	}
}
Code language: PHP (php)

This code will enqueue these scripts on your back end, if you want to, you can be more specific and say on what page you want these scripts included. That way you can include them only on posts, pages, media screen or settings screen for instance. I’ve created a gist for that as well, you can see here.

Back to our callback function. You define a function in which you’ll create a hidden input field – this will prevent the flashing of an empty (or full) input field before JavaScript kicks in and turns it into a color picker. First you create a variable to store the color: $header_color . This will either be the saved value, or empty if nothing is set.
You can also notice the nonce field. It’s a best practice to ensure that the forms aren’t submitted twice, and to check the origin of the data and the intent of the user – a security measure. Read more here and here. After the php part, just create your HTML container for the color picker. Some description text and the input field.

if ( ! function_exists( 'mytheme_header_meta_box' ) ) {
	function mytheme_header_meta_box( $post ) {
		$custom = get_post_custom( $post->ID );
		$header_color = ( isset( $custom['header_color'][0] ) ) ? $custom['header_color'][0] : '';
		wp_nonce_field( 'mytheme_header_meta_box', 'mytheme_header_meta_box_nonce' );
		?>
		<script>
		jQuery(document).ready(function($){
		    $('.color_field').each(function(){
        		$(this).wpColorPicker();
    		    });
		});
		</script>
		<div class="pagebox">
		    <p><?php esc_attr_e('Choose a color for your post header.', 'mytheme' ); ?></p>
		    <input class="color_field" type="hidden" name="header_color" value="<?php esc_attr_e( $header_color ); ?>"/>
		</div>
		<?php
	}
}
Code language: JavaScript (javascript)

I’ve also included the JavaScript code that will initialize the color picker. Now you might notice I’m using the .each() method here, and you are right to say: this is redundant! It is. You can easily replace it with $(‘.color_field’).wpColorPicker(); and it will work in this case. But if you want to add multiple color pickers – one for header of the article or page, one for title color or what ever you can think of, you’ll need to use the .each() method to target every input field that you want to ‘convert’ to color picker in your metabox.

All that is left is to save the meta box.

if ( ! function_exists( 'mytheme_save_header_meta_box' ) ) {
	function mytheme_save_header_meta_box( $post_id ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if( !current_user_can( 'edit_pages' ) ) {
			return;
		}
		if ( !isset( $_POST['header_color'] ) || !wp_verify_nonce( $_POST['mytheme_header_meta_box_nonce'], 'mytheme_header_meta_box' ) ) {
			return;
		}
		$header_color = (isset($_POST['header_color']) && $_POST['header_color']!='') ? $_POST['header_color'] : '';
		update_post_meta($post_id, 'header_color', $header_color);
	}
}

add_action( 'save_post', 'mytheme_save_header_meta_box' );Code language: PHP (php)

After that we have the color at our disposal in the post meta, and we can use it.

Color picker in a meta box
A finished meta box with color picker inside

And that’s it. You can add various meta boxes in various places within the WordPress back end, and use it as you wish. This is just one example that shows the versatility that WordPress offers.

If you like this tutorial be sure to share it, and comment if you have any questions below.

7 responses

  1. *Choose

    1. Hehe thanks for the fix :D

  2. Helpful post. When I search about it. Final it with this post.

  3. Hey there.
    Thanks this helped me alot. But if I want to input the hex value of the color?

    1. Yep, setting it to hidden will just hide the input field. I made it like that to be a bit neater, but you can set it to text and it will show :)

  4. sonia maklouf Avatar
    sonia maklouf

    Great tutorial Denis.
    I’ve got a suggestion for you
    why not a tuto on few others controls like you do for customizer ?
    Controls like text, numeric slider, toggle button or radio-image for example .
    What do you think ?

    1. Love the idea! Thanks for the suggestion. The related pages field article is also about the metabox control, I’ll go through the projects that I’ve worked on and make a list of all the additional controls I’ve made so far and I’ll create an article next week :)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.