<?php


add_action( 'load-post.php', 'perevod_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'perevod_post_meta_boxes_setup' );

function perevod_post_meta_boxes_setup() {
    
    add_action( 'add_meta_boxes', function (){
        add_meta_box(
            'perevod-post',
            'Перевод',
            'perevod_post_class_meta_box',
            'post',
            'side',
            'default'
        );
    });
    
    
    add_action( 'save_post', function ($post_id, $post){

        // проверяем, может ли текущий юзер редактировать пост
	    $post_type = get_post_type_object( $post->post_type );

        if ( ! current_user_can( $post_type->cap->edit_post, $post_id ) ) {
            return $post_id;
        }

        // ничего не делаем для автосохранений
	    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
		    return $post_id;
	    }
 

        $curr_id = 0;

        if( isset( $_POST[ 'perevod_name' ] )) {
            $curr_id = (int) $_POST[ 'perevod_name' ];
        }
        
        
        if ($curr_id == 0) {
            $meta_value = get_post_meta( $post_id, $meta_key, true );
            if ($meta_value !== false) {
                delete_post_meta( $post_id, 'perevod_name' );
            }
        } 
        else {   
            update_post_meta( $post_id, 'perevod_name', sanitize_text_field( $_POST[ 'perevod_name' ] ) );
        }

        return $post_id;


    }
    , 10, 2 );

    
}



function perevod_post_class_meta_box( $post ) {?>

    <?$args = array(
'role__in'     => array( 'administrator', 'author', 'editor' ),
'orderby'      => 'display_name',
'order'        => 'ASC',
);   
$authors = get_users( $args );
$perevod_name = get_post_meta( $post->ID, 'perevod_name', true );
?>

    <div class="components-base-control editor-post-excerpt__textarea">
        <div class="components-base-control__field">
           

            <div><label class="components-base-control__label" for="perevod_name">Выбрать переводчика</label></div>
                <div class="components-input-control__container css-ebmrdk-Container e1cr7zh11">
                    <select name="perevod_name" id="perevod_name" class="components-select-control__input">
                        <option value="0">-</option>
                        <?foreach ($authors as $author):?>
                            <option  value="<?=$author->ID?>" <?if ($author->ID == $perevod_name):?> selected<?endif?>><?=$author->display_name?></option>
                        <?endforeach?>    
                    </select>
                </div>
           
        </div>
    </div>
<?}