I have a custom metabox that have 2 options: URL and a text box called “testimonial”.
The URL box is working great(when i put some text in this field on admin, the text appears on site), but the testimonial box(same proposal) dont works.
What is wrong or what is missing?
<?php
add_action('admin_init', 'portfolio_meta_init');
function portfolio_meta_init() {
// add a meta box for WordPress 'project' type
add_meta_box('portfolio_meta', 'Project Infos', 'portfolio_meta_setup', 'project', 'side', 'low');
// add a callback function to save any data a user enters in
add_action('save_post', 'portfolio_meta_save');
}
function portfolio_meta_setup() {
global $post;
?>
<div class="portfolio_meta_control">
<label>URL</label>
<p>
<input type="text" name="_url" value="<?php echo get_post_meta($post->ID, '_url', TRUE); ?>" style="width: 100%;" />
</p>
<label>Testimonial</label>
<p>
<input type="text" name="_testimonial" value="<?php echo get_post_meta($post->ID, '_testimonial', TRUE); ?>" style="width: 100%;" />
</p>
</div>
<?php
// create for validation
echo '<input type="hidden" name="meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}
function portfolio_meta_save($post_id) {
// check nonce
if (!isset($_POST['meta_noncename']) || !wp_verify_nonce($_POST['meta_noncename'], __FILE__)) {
return $post_id;
}
// check capabilities
if ('post' == $_POST['post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
// exit on autosave
if (defined('DOING_AUTOSAVE') == DOING_AUTOSAVE) {
return $post_id;
}
if (isset($_POST['_url'])) {
update_post_meta($post_id, '_url', $_POST['_url']);
update_post_meta($post_id, '_testimonial', $_POST['_testimonial']);
} else {
delete_post_meta($post_id, '_url');
delete_post_meta($post_id, '_testimonial');
}
}
/* --- #end Demo URL meta box --- */ ?>
The outputs:
<?php echo get_post_meta($post->ID, '_testimonial', TRUE); ?>
<?php echo get_post_meta($post->ID, '_url', TRUE); ?>
Your above code should be working as is.
There is however one logical error at the end of your saving function – you make the saving of both fields dependent on whether
$_POST['_url']
is set.I suppose that is not intentional. You likely want something along the lines of:
While the above is likely the functionality you are looking for, it isn’t very efficient if you have more than two custom fields to save (or create), so I’d suggest you do something like this: