<?php
	/**
	 * Plugin Name: Category Icon
	 * Description: Category Icon field for category taxonomy
	 * Version: 1.0
	 */

	/**
	 * Field on category create screen
	 */
	add_action( 'category_add_form_fields', function () {
		?>
		<div class="form-field term-icon-wrap">
			<label for="term-icon">Icon</label>
			<input
				type="text"
				name="term_icon"
				id="term-icon"
				value=""
			>
			<p>Example: 💰, 🍩, 🪙</p>
		</div>
		<?php
	} );

	/**
	 * Field on category edit screen
	 */
	add_action(
		'category_edit_form_fields',
		function ( $term ) {

			$icon = get_term_meta( $term->term_id, 'icon', true );
			?>
			<tr class="form-field term-icon-wrap">
				<th scope="row">
					<label for="term-icon">Icon</label>
				</th>
				<td>
					<input
						type="text"
						name="term_icon"
						id="term-icon"
						value="<?php echo esc_attr( $icon ); ?>"
					>
					<p class="description">
						Example: 💰, 🍩, 🪙
					</p>
				</td>
			</tr>
			<?php
		}
	);

	/**
	 * Save on create
	 */
	add_action(
		'created_category',
		function ( $term_id ) {

			if ( isset( $_POST['term_icon'] ) ) {
				update_term_meta(
					$term_id,
					'icon',
					sanitize_text_field( wp_unslash( $_POST['term_icon'] ) )
				);
			}
		}
	);

	/**
	 * Save on edit
	 */
	add_action(
		'edited_category',
		function ( $term_id ) {

			if ( isset( $_POST['term_icon'] ) ) {
				update_term_meta(
					$term_id,
					'icon',
					sanitize_text_field( wp_unslash( $_POST['term_icon'] ) )
				);
			}
		}
	);