config = json_decode( $this->config, true );
add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
add_action( 'save_post', [ $this, 'save_post' ] );
}
public function add_meta_boxes() {
foreach ( $this->config['post-type'] as $screen ) {
add_meta_box(
sanitize_title( $this->config['title'] ),
$this->config['title'],
[ $this, 'add_meta_box_callback' ],
$screen,
$this->config['context'],
$this->config['priority']
);
}
}
public function save_post( $post_id ) {
foreach ( $this->config['fields'] as $field ) {
switch ( $field['type'] ) {
default:
if ( isset( $_POST[ $field['id'] ] ) ) {
$sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
update_post_meta( $post_id, $field['id'], $sanitized );
}
}
}
}
public function add_meta_box_callback() {
$this->fields_div();
}
public function fields_div() {
global $post;
$post_type = $post->post_type;
foreach ( $this->config['fields'] as $field ) {
// Check if post type is 'page', if so, show all fields
// Otherwise, show only sidebar settings
if ( $post_type === 'page' || $field['id'] === 'author_blog_sidebar-settings' ) {
?>
label( $field );
$this->field( $field );
?>
%s',
$field['id'], $field['label']
);
}
}
private function field( $field ) {
switch ( $field['type'] ) {
case 'select':
$this->select( $field );
break;
default:
$this->input( $field );
}
}
private function input( $field ) {
printf(
'',
isset( $field['class'] ) ? $field['class'] : '',
$field['id'], $field['id'],
isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
$field['type'],
$this->value( $field )
);
}
private function select( $field ) {
printf(
'',
$field['id'], $field['id'],
$this->select_options( $field )
);
}
private function select_selected( $field, $current ) {
$value = $this->value( $field );
if ( $value === $current ) {
return 'selected';
}
return '';
}
private function select_options( $field ) {
$output = [];
$options = explode( "\r\n", $field['options'] );
$i = 0;
foreach ( $options as $option ) {
$pair = explode( ':', $option );
$pair = array_map( 'trim', $pair );
$output[] = sprintf(
'',
$this->select_selected( $field, $pair[0] ),
$pair[0], $pair[1]
);
$i++;
}
return implode( '
', $output );
}
private function value( $field ) {
global $post;
if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
$value = get_post_meta( $post->ID, $field['id'], true );
} else if ( isset( $field['default'] ) ) {
$value = $field['default'];
} else {
return '';
}
return str_replace( '\u0027', "'", $value );
}
}
new Author_Blog_Meta_Box;