WordPress.org

Support

Support » Plugins and Hacks » Hacks » Blank values appearing with 'add_meta_box' function

Blank values appearing with 'add_meta_box' function

  • Hi,

    I’m using the add_meta_box() function in functions.php to add custom fields to the WP post page. The way I’ve implemented it is a bit of a hack, however (1000 posts later…) I’ve noticed that even if I don’t use the metaboxes it still creates an entry in the DB with a blank value for ‘meta_value’ for each new post. Obviously this is not ideal.

    Values from these metaboxes are stored as custom fields.

    Do you know of any way to ensure new DB entries are only made when something is selected or entered within the new meta box?

    The main part of the existing code is as follows:

    add_action('admin_menu', 'BOX_NAME');
    
    	function BOX_NAME() {
    		add_meta_box('OPTION 1');
    		add_meta_box('OPTION 2');
      	}
    
    add_action('save_post', 'custom_save');
    
    function custom_save($postID){
    
    	// called after a post or page is saved
    	if($parent_id = wp_is_post_revision($postID))
    	{
    	  $postID = $parent_id;
    	}
    	if ($_POST['save'] || $_POST['publish']) {
    
    		update_custom_meta($postID, $_POST['ID 1'], 'ID 4');
    		update_custom_meta($postID, $_POST['ID 2'], 'ID 5');
     		update_custom_meta($postID, $_POST['ID 3'], 'ID 6');
      	}
    }
    
    function update_custom_meta($postID, $newvalue, $field_name) {
    	// Create new meta
    	if(!get_post_meta($postID, $field_name)){
    	add_post_meta($postID, $field_name, $newvalue);
    	}else{
    	// or Update Meta
    	update_post_meta($postID, $field_name, $newvalue);
    	}
    }

    I’d really appreciate any insight you can offer on this issue.

Viewing 2 replies - 1 through 2 (of 2 total)
  • bcworkz
    Participant

    @bcworkz

    Your function should not attempt to update or add the post_meta if the associated form field value remains unset.
    if (isset($_POST['ID 1'])) update_custom_meta($postID, $_POST['ID 1'], 'ID 4');

    Also ensure whatever uses the meta data properly handles the lack of a meta record.

    michael.mariart
    Member

    @michaelmariart

    There’s another thing that happens when a post is saved that they don’t tell you about… and it causes a lot of headaches.

    If your post does an auto-save, it doesn’t include any of the fields in your meta boxes, it only includes the standard WordPress fields. As a good check, I use something like this:

    function savePost () {
    	global $post;
    
    	if (defined ("DOING_AUTOSAVE") && DOING_AUTOSAVE || get_post_type ($post) != "my_post_type") {
    		return "";
    	}
    	else {
    		update_post_meta ($post->ID, "value_name", $_POST ["value"]);
    	}
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Blank values appearing with 'add_meta_box' function’ is closed to new replies.