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:
if ( isset( $_POST['_url'] ) ) {
update_post_meta( $post_id, '_url', $_POST['_url'] );
} else {
delete_post_meta( $post_id, '_url' );
}
if ( isset($_POST['_testimonial'] ) ) {
update_post_meta( $post_id, '_testimonial', $_POST['_testimonial'] );
} else {
delete_post_meta( $post_id, '_testimonial' );
}
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:
class WPSE_95952_meta
{
private $fields = array(
array(
'name' => '_url',
'label' => 'URL'
),
array(
'name' => '_testimonial',
'label' => 'Testimonial'
)
);
public function __construct()
{
// add a meta box for WordPress 'project' type
add_action( 'add_meta_boxes', array( $this, 'add_project_box' ) );
// add a callback function to save any data a user enters in
add_action( 'save_post', array( $this, 'portfolio_meta_save' ) );
}
public function add_project_box()
{
add_meta_box(
'portfolio_meta',
'Project Infos',
array( $this, 'portfolio_meta_setup' ),
'project',
'side',
'low'
);
}
public function portfolio_meta_setup()
{
global $post;
$output="<div class="portfolio_meta_control">";
foreach ( $this->fields as $field ) {
$output .= '<label>' . $field['label'] . '</label>' .
'<p>' .
'<input type="text" name="' . $field['name'] .
'" value="' . get_post_meta( $post->ID, $field['name'], true ) .
'" style="width: 100%;" />' .
'</p>';
}
$output .= '</div>';
// create for validation
$output .= '<input type="hidden" name="meta_noncename" value="' .
wp_create_nonce(__FILE__) . '" />';
echo $output;
}
public function portfolio_meta_save( $post_id )
{
// exit on autosave
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $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'] && ! current_user_can( 'edit_post', $post_id ) ) ||
! current_user_can( 'edit_page', $post_id )
) {
return $post_id;
}
foreach ( $this->fields as $field ) {
$old = get_post_meta( $post_id, $field['name'], true );
$new = isset( $_POST[$field['name']] ) ? $_POST[$field['name']] : false;
if ( $new && $new != $old ) {
update_post_meta( $post_id, $field['name'], $new );
} elseif ( ! $new && $old ) {
delete_post_meta( $post_id, $field['name'], $old );
}
}
}
}
$wpse_95952_meta = new WPSE_95952_meta();