Skip to content

Instantly share code, notes, and snippets.

@nextab
Last active April 22, 2021 14:13
Show Gist options
  • Save nextab/99571adee0c7ce246e295e376faf8e61 to your computer and use it in GitHub Desktop.
Save nextab/99571adee0c7ce246e295e376faf8e61 to your computer and use it in GitHub Desktop.
/* Konkretes Beispiel: Metabox mit einem 2ter Autor wird angezeigt und es wird in das custom field "2nd author" der Wert eingetragen (so dass man den Wert theoretisch auch über Bearbeitung der custom field metabox (als Teil des WordPress Cores) bearbeiten könnte).
(Wenn man das Custom Field "_2nd author" nennen würde, dann würde es dort nicht angezeigt werden -> Präfix _ sorgt dafür, dass es nur in der Datenbank angezeigt wird und nicht in der Metabox der custom fields.) */
// Add a Metabox to the backend
function add_nxt_author_meta_box() {
add_meta_box("nxt-author-meta-box", "2nd Author", "nxt_author_meta_box_markup", "post", "side", "high", null);
}
add_action("add_meta_boxes", "add_nxt_author_meta_box");
// Fill Metabox with our custom variable
function nxt_author_meta_box_markup() {
wp_nonce_field(basename(__FILE__), "nxt-author-meta-box-nonce");
if(get_post_meta(get_the_ID(), '2nd author', true) != '') {
$nxt_current_second_author = get_post_meta(get_the_ID(),'2nd author',true);
wp_dropdown_users(array( 'name' => 'nxt_second_author', 'show_option_none' => '---', 'selected' => $nxt_current_second_author ));
} else wp_dropdown_users(array( 'name' => 'nxt_second_author', 'show_option_none' => '---' ));
}
// Save value of Metabox
function save_nxt_author_meta_box($post_id) {
// check nonce to avoid hacker shit
if (!isset($_POST["nxt-author-meta-box-nonce"]) || !wp_verify_nonce($_POST["nxt-author-meta-box-nonce"], basename(__FILE__))) return $post_id; // else echo "<!-- debug - did not make it through nonce check! -->";
// check permissions of user
if(!current_user_can("edit_post", $post_id)) return $post_id;
// make sure this isn't an auto-save
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) return $post_id;
// echo "<!-- debug - this is not an autosave -->";
// make sure this is only being displayed for pages
$slug = "page";
if( $slug != get_post_type($post_id)) return $post_id;
if((isset($_POST["nxt_second_author"])) && ($_POST["nxt_second_author"] <> '-1' )) {
// echo "<!-- debug - nxt_second_author is set in POST variable - value: " . $_POST['nxt_second_author'] . " -->";
$meta_box_text_value = $_POST["nxt_second_author"];
update_post_meta($post_id, "2nd author", $_POST["nxt_second_author"]);
} else {
delete_post_meta($post_id, "2nd author");
}
}
add_action('save_post', 'save_nxt_author_meta_box', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment