Post Author Metabox
class Sgr_post_author_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(
'post_author_meta',
__( 'Autor', 'sgr' ),
array( $this, 'render_post_author_meta_box' ),
'post',
'side',
'high'
);
}
public function render_post_author_meta_box( $post ) {
// Add nonce for security and authentication.
wp_nonce_field( 'sgr_nonce_action', 'sgr_nonce' );
// Retrieve an existing value from the database.
$sgr_meta_post_author = get_post_meta( $post->ID, 'sgr_meta_post_author', true );
// Set default values.
if( empty( $sgr_meta_post_author ) ) $sgr_meta_post_author = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="sgr_meta_post_author" class="sgr_meta_post_author_label">' . __( 'Autor', 'sgr' ) . '</label></th>';
echo ' <td>';
echo ' <input type="text" id="sgr_meta_post_author" name="sgr_meta_post_author" class="sgr_meta_post_author_field" placeholder="' . esc_attr__( '', 'sgr' ) . '" value="' . esc_attr( $sgr_meta_post_author ) . '">';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Add nonce for security and authentication.
$nonce_name = isset( $_POST['sgr_nonce'] ) ? $_POST['sgr_nonce'] : '';
$nonce_action = 'sgr_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.
$sgr_new_meta_post_author = isset( $_POST[ 'sgr_meta_post_author' ] ) ? sanitize_text_field( $_POST[ 'sgr_meta_post_author' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'sgr_meta_post_author', $sgr_new_meta_post_author );
}
}
new Sgr_post_author_Meta_Box;