Or, embed this snippet using GenerateWP WordPress Plugin.

Download

Clone

Untitled Snippet

class Market_Meta_Box {

	public function __construct() {

		if ( is_admin() ) {
			add_action( 'load-post.php',     array( $this, 'init_metabox' ) );
			add_action( 'load-post-new.php', array( $this, 'init_metabox' ) );
		}

	}

	public function init_metabox() {

		add_action( 'add_meta_boxes',        array( $this, 'add_metabox' )         );
		add_action( 'save_post',             array( $this, 'save_metabox' ), 10, 2 );

	}

	public function add_metabox() {

		add_meta_box(
			'market_meta_box',
			__( 'Market Meta Box', 'text_domain' ),
			array( $this, 'render_metabox' ),
			'service',
			'normal',
			'high'
		);

	}

	public function render_metabox( $post ) {

		// Add nonce for security and authentication.
		wp_nonce_field( 'mmb_nonce_action', 'mmb_nonce' );

		// Retrieve an existing value from the database.
		$mmb_sa_tax = get_post_meta( $post->ID, 'mmb_sa_tax', true );

		// Set default values.
		if( empty( $mmb_sa_tax ) ) $mmb_sa_tax = '';

		// Form fields.
		echo '<table class="form-table">';

		echo '	<tr>';
		echo '		<th><label for="mmb_sa_tax" class="mmb_sa_tax_label">' . __( 'Service Area', 'text_domain' ) . '</label></th>';
		echo '		<td>';
		wp_dropdown_categories( array( 'id' => 'mmb_sa_tax', 'name' => 'mmb_sa_tax', 'class' => 'mmb_sa_tax_field', 'selected' => $mmb_sa_tax ) );
		echo '			<p class="description">' . __( 'Service Area', 'text_domain' ) . '</p>';
		echo '		</td>';
		echo '	</tr>';

		echo '</table>';

	}

	public function save_metabox( $post_id, $post ) {

		// Add nonce for security and authentication.
		$nonce_name   = isset( $_POST['mmb_nonce'] ) ? $_POST['mmb_nonce'] : '';
		$nonce_action = 'mmb_nonce_action';

		// Check if a nonce is set.
		if ( ! isset( $nonce_name ) )
			return;

		// Check if a nonce is valid.
		if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) )
			return;

		// Check if the user has permissions to save data.
		if ( ! current_user_can( 'edit_post', $post_id ) )
			return;

		// Check if it's not an autosave.
		if ( wp_is_post_autosave( $post_id ) )
			return;

		// Check if it's not a revision.
		if ( wp_is_post_revision( $post_id ) )
			return;

		// Sanitize user input.
		$mmb_new_sa_tax = isset( $_POST[ 'mmb_sa_tax' ] ) ? sanitize_text_field( $_POST[ 'mmb_sa_tax' ] ) : '';

		// Update the meta field in the database.
		update_post_meta( $post_id, 'mmb_sa_tax', $mmb_new_sa_tax );

	}

}

new Market_Meta_Box;