Headings meta bxes
class Offer_Headings {
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(
'headings',
__( 'Overskrifter', 'Offer' ),
array( $this, 'headings_callback' ),
'page',
'normal',
'low'
);
}
public function headings_callback( $post ) {
// Add nonce for security and authentication.
wp_nonce_field( 'nonce_action', 'nonce' );
// Retrieve an existing value from the database.
$heading = get_post_meta( $post->ID, 'heading', true );
$subheading = get_post_meta( $post->ID, 'subheading', true );
// Set default values.
if( empty( $heading ) ) $heading = '';
if( empty( $subheading ) ) $subheading = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="heading" class="heading_label">' . __( 'Overskrift', 'Offer' ) . '</label></th>';
echo ' <td>';
echo ' <textarea id="heading" name="heading" class="heading_field" placeholder="' . esc_attr__( '', 'Offer' ) . '">' . $heading . '</textarea>';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="subheading" class="subheading_label">' . __( 'Underoverskrift', 'Offer' ) . '</label></th>';
echo ' <td>';
echo ' <textarea id="subheading" name="subheading" class="subheading_field" placeholder="' . esc_attr__( '', 'Offer' ) . '">' . $subheading . '</textarea>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Add nonce for security and authentication.
$nonce_name = isset( $_POST['nonce'] ) ? $_POST['nonce'] : '';
$nonce_action = '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;
// Sanitize user input.
$new_heading = isset( $_POST[ 'heading' ] ) ? sanitize_text_field( $_POST[ 'heading' ] ) : '';
$new_subheading = isset( $_POST[ 'subheading' ] ) ? sanitize_text_field( $_POST[ 'subheading' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'heading', $new_heading );
update_post_meta( $post_id, 'subheading', $new_subheading );
}
}
new Offer_Headings;