Meta Box Category Colors in Single Posts

Looking to use Meta Box Color Picker fields’ values in a single post Bricks template based on the post category?

This tutorial shows how.

Note: Designed to work mainly for the case where posts have a single category assigned to each.

Step 1

Create a field group named say, “Category Fields” having category_primary_color and category_secondary_color fields of the type, Color Picker.

Location: Category taxonomy.

Step 2

Edit your categories and pick colors for both the fields.

Step 3

Let’s define a custom function that returns the color based on the specified type, primary or secondary or, if the color is not set a fallback/default color.

Add the following in child theme‘s functions.php or a code snippets plugin:

// Avoid Undefined Function Error when Meta Box is not active.
if ( ! function_exists( 'rwmb_meta' ) ) {
	function rwmb_meta( $key, $args = '', $post_id = null ) {
			return false;
	}
}

// Custom function to get the value of the category color meta field.
function bl_get_category_color_in_post( string $type ): string {
		$color = rwmb_meta( "category_{$type}_color", [ 'object_type' => 'term' ], wp_get_post_categories( get_the_ID() )[0] );

		return $color ? $color : '#333'; // fallback color
}

Step 4

Edit your single post template with Bricks.

For setting the category primary color or category secondary color field’s value as the background color of an element, click on the color picker, then RAW and paste:

{echo:bl_get_category_color_in_post(primary)}

The above will set the value of category_primary_color field as the background color.

For secondary, you’d instead do:

{echo:bl_get_category_color_in_post(secondary)}

You can similarly set one of these two fields’ values as Color if you wish.

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

2 comments

Leave your comment