0 points

Select for custom taxonomy


dashboard

Sat Oct 24 2020 09:59:54 GMT+0000 (UTC)

Posted by @Krumil #php #taxonomy

	function qzr_page_target_meta_box( $post) {
		$qzr_targets = get_terms([
			'taxonomy' => 'qzr_target',
			'hide_empty' => false,
		]);

		$current_targets = get_the_terms($post->ID,'qzr_target');

		if(is_array($current_targets)) {
			$current_term_slug = count($current_targets) > 1? 'all' : $current_targets[0]->slug;
		}
		else {
			$current_term_slug = false;
		}
	?>
		<select name="qzr_target" class="qzr_target">
			<?= !$current_term_slug ? '<option selected disabled>Seleziona un target</option>' : '' ?>
			<?php foreach($qzr_targets as $target): ?>
				<option value="<?= $target->slug?>" <?= $target->slug == $current_term_slug? 'selected' : '' ?>>
				<?= $target->name?>
			</option>	
			<?php endforeach?>
		</select>
		<?php
	}

	function qzr_save_target_meta( $post_id ){
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		return $post_id;
		if(isset($_POST['qzr_target'])) {
			if($_POST['qzr_target'] == 'all') {
				$qzr_targets = get_terms([
					'taxonomy' => 'qzr_target',
					'hide_empty' => false,
				]);
				$all_targets = [];

				foreach($qzr_targets as $target) {
					array_push($all_targets,$target->term_id);
				}
				wp_set_post_terms( $post_id, $all_targets, 'qzr_target' );	
			}
			else {
				$term = get_term_by( 'slug',$_POST['qzr_target'], 'qzr_target' );
				if($term->term_id > 0) {
					wp_set_post_terms( $post_id, array( $term->term_id ), 'qzr_target' );
				}
			}
		}
	}
	add_action( 'save_post', 'qzr_save_target_meta', 10, 2 );

	function qzr_post_target_meta() {
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','page','side','high' );
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','post','side','high' );
		add_meta_box( 'qzr_page_target', 'Target', 'qzr_page_target_meta_box','project','side','high' );
	}
	add_action( 'admin_init', 'qzr_post_target_meta' );
content_copy Copy

Biblioteca

https://jsfiddle.net/