Skip to content

Instantly share code, notes, and snippets.

@frontend-coder
Last active July 15, 2022 16:47
Show Gist options
  • Save frontend-coder/1d2d393275a31d4db13894f14ecf86de to your computer and use it in GitHub Desktop.
Save frontend-coder/1d2d393275a31d4db13894f14ecf86de to your computer and use it in GitHub Desktop.
21.1. Як створити власний метабокс Wordpress #wordpress
function domein_add_metabox() {
add_neta_box('car_metabox', esc_html__('Cars Settings','domein'), 'domeins_cars_metabox_html', 'cars');
}
add_action('add_meta_boxes', 'domein_add_metabox');
function domeins_cars_metabox_html(){
$car_price = get_post_meta($post->ID, 'car_price', true);
$car_engine = get_post_meta($post->ID, 'car_engine', true);
wp_nonce_field('domeinrandomstring', '_carmetabox');
?>
<div>
<label for="car_price"><?php esc_html_e('Car Price', ''); ?> </label>
<input type="text" id="car_price" name="car_price" value="<?php echo esc_attr($car_price); ?>" >
</div>
<div>
<label for="car_engine"><?php esc_html_e('Car Engine', ''); ?> </label>
<selection id="car_engine" name="car_engine" >
<option value="" > Make change</option>
<option value="manual" <?php if($car_engine == 'manual') { echo 'selected'} ?> >Manual</option>
<option value="automatic" <?php if($car_engine == 'automatic') { echo 'selected'} ?> > Automatic</option>
</section>
</div>
<?php
}
function domain_save_metabox($post_id, $post) {
if( !isset($_POST['_carmetabox'] ) || !wp_verify_nonce($_POST['_carmetabox'], 'domeinrandomstring' ) ) {
return $post_id;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $post_id;
}
if( $post->post_type != 'car' ) {
return $post_id;
}
$postType = get_post_type_object($post->post_type);
if( !current_user_can($postType->cap->edit_post, $post_id ) {
return $post_id;
}
if(isset($_POST['car_price']) ) {
update_post_meta($post_id, 'car_price', sanitize_text_field($_POST['car_price'] ) );
} else {
delete_post_meta($post_id, 'car_price');
}
if(isset($_POST['car_engine']) ) {
update_post_meta($post_id, 'car_engine', sanitize_text_field($_POST['car_engine'] ) );
} else {
delete_post_meta($post_id, 'car_engine');
}
return $post_id;
}
add_action('save_post', 'domain_save_metabox', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment