Add Custom Optgroups to kirki Typography Dropdown

In this quick tutorial, we’re learning how to add custom optgroups to kirki’s typography dropdown.

To get started, we create a very basic typography field with kirki.

// Font Family
Kirki::add_field( 'my_theme_config', array(
'type' => 'typography',
'settings' => 'page_font_family',
'label' => esc_attr__( 'Font', 'textdomain' ),
'section' => 'my_theme_font_options',
'default' => array(
'font-family' => 'Helvetica, Arial, sans-serif',
'variant' => 'regular',
),
'choices' => my_theme_default_font_choices(),
'priority' => 1
) );

Notice that for “choices” we’re calling my_theme_default_font_choices(). This is where the magic is going to happen. We’re going to use that function to filter the choices argument and add our optgroup. Here’s what the function looks like:

// Default Font Choice
function my_theme_default_font_choices(){
return array(
'fonts' => apply_filters( 'my_theme_font_choices', array() )
);
}

To better understand the choices argument, let me point you to the kirki documentation.

Now it’s time to add our custom optgroup using the filter above.

// Custom Font Group
function my_custom_optgroup( $custom_choice ) {

	$custom_choice['families']['custom_fonts'] = array(
		'text'		=> esc_attr__( 'Custom Fonts', 'textdomain' ),
		'children'	=> array(
			array( 'id' => 'ProximaNova', 'text' => 'Proxima Nova' ),
		),
	);

	$custom_choice['variants'] = array(
		'ProximaNova'	=> array( '200', '300', '400', '400italic', '500', '500italic', '600', '600italic', '700', '700italic', '800', '800italic', 'regular', 'italic' ),
	);

	return $custom_choice;

}

add_filter( 'my_theme_font_choices', 'my_custom_optgroup', 20 );

In the first part of the filter, we’re adding our custom_fonts optgroup to the families array by defining our optgroup title (text) and the actual font (children) consisting of a unique ID & title.

In the second part, we add the variants we want to be available for that specific font.

Done! 🙂

You’ve successfully added a custom optgroup to the kirki typography dropdown.

Leave a Comment

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