demo for tomas
class TP_Primo_Featured_Image_Options_Custom_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(
'featured-image-options',
__( 'Featured Image Options', 'tp-primo' ),
array( $this, 'render_tp_primo_featured_image_options_metabox' ),
array( 'post', 'page' ),
'side',
'default'
);
}
public function render_tp_primo_featured_image_options_metabox( $post ) {
// Add nonce for security and authentication.
wp_nonce_field( 'tp_primo_nonce_action', 'tp_primo_nonce' );
// Retrieve an existing value from the database.
$tp_primo_where_to_show = get_post_meta( $post->ID, 'tp_primo_where_to_show', true );
// Set default values.
if( empty( $tp_primo_where_to_show ) ) $tp_primo_where_to_show = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="tp_primo_where_to_show" class="tp_primo_where_to_show_label">' . __( 'Where to Show', 'tp-primo' ) . '</label></th>';
echo ' <td>';
echo ' <label><input type="radio" name="tp_primo_where_to_show" class="tp_primo_where_to_show_field" value="tp_primo_above" ' . checked( $tp_primo_where_to_show, 'tp_primo_above', false ) . '> ' . __( 'Show Above Title', 'tp-primo' ) . '</label><br>';
echo ' <label><input type="radio" name="tp_primo_where_to_show" class="tp_primo_where_to_show_field" value="tp_primo_bellow" ' . checked( $tp_primo_where_to_show, 'tp_primo_bellow', false ) . '> ' . __( 'Show Below Title', 'tp-primo' ) . '</label><br>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Add nonce for security and authentication.
$nonce_name = isset( $_POST['tp_primo_nonce'] ) ? $_POST['tp_primo_nonce'] : '';
$nonce_action = 'tp_primo_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.
$tp_primo_new_where_to_show = isset( $_POST[ 'tp_primo_where_to_show' ] ) ? $_POST[ 'tp_primo_where_to_show' ] : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'tp_primo_where_to_show', $tp_primo_new_where_to_show );
}
}
new TP_Primo_Featured_Image_Options_Custom_Meta_Box;