Skip to content

Instantly share code, notes, and snippets.

@artursopelnik
Last active October 4, 2017 09:53
Show Gist options
  • Save artursopelnik/fc1a1d463bf9f40ae73986443de6b6ec to your computer and use it in GitHub Desktop.
Save artursopelnik/fc1a1d463bf9f40ae73986443de6b6ec to your computer and use it in GitHub Desktop.
Add meta box, print content and save_post. Read more: https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/
<?php
add_action('add_meta_boxes', 'add_country_name_meta_box');
function add_country_name_meta_box()
{
add_meta_box(
'country_name_meta_box',
__('Widget Title', 'theme_name'),
'add_country_name_meta_box_callback', // Prints the box content
'post', // $page
'normal', // $context
'high' // $priority
);
}
function add_country_name_meta_box_callback($post, $metabox)
{
$value = esc_attr(get_post_meta($post->ID, 'country_name', true));
wp_nonce_field(basename(__FILE__), 'country_name_nonce'); ?>
<label for="country_name">
<?php _e('Widget Label: ', 'theme_name'); ?>
</label>
<select name="country_name" id="country_name">
<option value="" selected><?php _e('Please choose', 'theme_name'); ?></option>
<option value="germany" <?php if($value == 'germany'): ?>selected<?php endif; ?>>Deutschland</option>
<option value="usa" <?php if($value == 'usa'): ?>selected<?php endif; ?>>USA</option>
</select> <?php
}
// Save post meta on the 'save_post' hook.
add_action('save_post', 'save_country_name', 10, 2);
function save_country_name($post_id, $post)
{
/* Verify the nonce before proceeding. */
if (!isset($_POST['country_name_nonce']) || !wp_verify_nonce($_POST['country_name_nonce'], basename(__FILE__)))
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object($post->post_type);
/* Check if the current user has permission to edit the post. */
if (!current_user_can($post_type->cap->edit_post, $post_id))
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = (isset($_POST['country_name']) ? sanitize_html_class($_POST['country_name']) : '');
/* Get the meta key. */
$meta_key = 'country_name';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta($post_id, $meta_key, true);
/* If a new meta value was added and there was no previous value, add it. */
if ($new_meta_value && '' == $meta_value)
add_post_meta($post_id, $meta_key, $new_meta_value, true);
/* If the new meta value does not match the old value, update it. */
elseif ($new_meta_value && $new_meta_value != $meta_value)
update_post_meta($post_id, $meta_key, $new_meta_value);
/* If there is no new meta value but an old value exists, delete it. */
elseif ('' == $new_meta_value && $meta_value)
delete_post_meta($post_id, $meta_key, $meta_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment