Here is the full code right now. Kind of messy I know:
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'meta_key' => '_kjm_is_service',
'meta_value' => '1'
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$kjm_alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$kjm_image_title = $attachment->post_title;
$kjm_url = wp_get_attachment_url( $attachment->ID , false );
}
}
$meta_box['service'] = array(
'id' => 'service-details',
'title' => 'Service Details',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'background-image',
'desc' => 'bla bla bla',
'id' => 'service-bg',
'type' => 'radio',
'options' => array(
array('name' => 'Name 1', 'value' => 'Value 1'),
array('name' => 'Name 2', 'value' => 'Value 2'),
array('name' => $kjm_url, 'value' => $kjm_url)
)
)
)
);
add_action('admin_menu', 'kjm_add_box');
//Add meta boxes to post types
function kjm_add_box() {
global $meta_box;
foreach($meta_box as $post_type => $value) {
add_meta_box($value['id'], $value['title'], 'kjm_format_box', $post_type, $value['context'], $value['priority']);
}
}
//Format meta boxes
function kjm_format_box() {
global $meta_box, $post;
//print_r(array_values($meta_box));
// Use nonce for verification
echo '<input type="hidden" name="kjm_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($meta_box[$post->post_type]['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>'.
'<th style="width:20%"><label for="'. $field['id'] .'">'. $field['name']. '</label></th>'.
'<td>';
switch ($field['type']) {
case 'radio':
foreach ($field['options'] as $option) {
echo '<input type="radio" name="' . $field['id'] . '" value="' . $option['value'] . '"' . ( $meta == $option['value'] ? ' checked="checked"' : '' ) . ' />' . $option['name'];
}
break;
}
}
echo '<td>'.'</tr>';
}
echo '</table>';
}
// Save data from meta box
function kjm_save_data($post_id) {
global $meta_box, $post;
//Verify nonce
if (!wp_verify_nonce($_POST['kjm_meta_box_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;
}
foreach ($meta_box[$post->post_type]['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}
add_action('save_post', 'kjm_save_data');
The data does save but this currently just returns the first two static options plus one with the most recent URL from the $attachments query.