Working with icons

Using the t2 icons-package provides a simple and scalable way to use icons in your projects. In this guide, we'll take a hands on approach to working with icons.

link Adding icons

T2 comes with a set of predefined icons that can be used in your project. The available icons can be extended or overwritten using the t2-icons-filter. The icons-array follows a key=>value structure where the key is the slug of the icon and the value is the path part of the svg-element.

Place the following snippet in your project setup file, and extend it with any customer specific icons that are needed.

add_filter( 't2_icons', 'guides_register_t2_icons' );

function guides_register_t2_icons( array $icons ) : array {
	return array_merge( $icons, [
		'icon-slug' => '<path d="M8.09 18.71a.996.996 5.3a.996.996 0 01-1.41 0z"/>',
	] );
}

link Using icons in php

After extending the icons with your project specific needs, you can use them easily in your code.

The following snippet shows how to use the icons in a sprintf-function.

use function T2\Icons\get_icon;

return sprintf( '
	<div %s>
		<span class="guides-icon-heading__icon">%s</span>
		<span class="guides-icon-heading__title">%s</span>
	</div>',
	$block_attributes,
	get_icon( 'icon-slug', 24, 'guide-icon__red' ),
	$title
);

The get_icon-function returns the svg-element for the icon as a string.

The same arguments can be used in the icon-function, which prints the svg to the page.

use function T2\Icons\icon;

<div class="site-header--branding">
	<?php icon( 'icon-slug', 24, 'guide-icon__red' ); ?>
</div>

link Using icons in JavaScript

T2 comes with a set of helper components that can be used to render icons in JavaScript.

The following snippet shows you how you can leverage t2 icons together with the t2 editor package to work with icons in your blocks.

import { BlockControls } from '@wordpress/block-editor';

import { Icon, BlockIconSelector } from '@t2/editor';

const edit = ({attributes, setAttributes}) => {
	const { icon } = attributes;

	return (
		<>
			<BlockControls>
				<BlockIconSelector
					allowedIcons={ ['smiley', 'question', 'icon-slug'] }
					onSelect={ ( newIcon ) => setAttributes( { icon: newIcon } ) }
					selected={ icon }
				/>
			</BlockControls>
			<div>
				<Icon icon={icon} size={40} />
			</div>
		</>
	)
}

The BlockIconSelector is a component that can be used to select an icon from the t2_icons-array we defined earlier. It shows all of the icons in a popover, and allows you to select one.

The Icon component is a helper component that renders the svg-element for the icon.

To use the icon you stored as an attribute in the server side render callback, you can use the icon or get_icon-function.

use function T2\Icons\get_icon;

return sprintf( '
	<div %s>
		%s
	</div>',
	$block_attributes,
	get_icon( $attributes['icon'], 40 ),
	$title
);