save metabox with new values _wp_page_template

Question

I created a metabox to display the page templates and select a different one with a radiobutton selection. This is a replacement for the current page attributes metabox.

I’m missing something with the saving part. The _wp_page_template doesn’t get updated.
Here is what I currently have:

<?php 
// Add the Meta Box
function add_meta_box_template_picker() {
add_meta_box(
    'meta_box_template_picker', // $id
    'Template Picker', // $title
    'show_meta_box_template_picker', // $callback
    'page', // $page
    'normal', // $context
    'high'); // $priority
}
add_action('add_meta_boxes', 'add_meta_box_template_picker');

// The Callback
function show_meta_box_template_picker() {
$templates = get_page_templates(); 
foreach ( $templates as $template_name => $template_filename ) {
   if ($template_filename == 'template1.php' || 
       $template_filename == 'template2.php' || 
       $template_filename == 'template3.php' ){
        echo "<input type='radio' name='_wp_page_template' value='$template_filename' />$template_name<br />";         
   }else{
        echo '';
   }
}
}
// Save the Data
function save_custom_meta($post_id) {
global $templates, $post; // post of template
 $post_id = $post->ID;
// verify nonce
if (!wp_verify_nonce($_POST['meta_box_template_picker_nonce'], basename(__FILE__)))
    return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    return $post_id;
// check permissions
if ('page' == $_POST['post_type']) {
    if (!current_user_can('edit_page', $post_id))
        return $post_id;
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
}

// loop through fields and save the data
    $old = get_post_meta($post_id, '_wp_page_template', true);
    $new = $_POST['_wp_page_template'];
    if ($new && $new != $old) {
        update_post_meta($post_id, '_wp_page_template', $new);
    } elseif ('' == $new && $old) {
        delete_post_meta($post_id, '_wp_page_template', $old);
    }
} // end foreach

add_action('save_post', 'save_custom_meta');

?>

Hope somebody sees what I’m doing wrong.

0
, , Interactive 8 months 0 Answers 109 views 0

Leave an answer