How to set a default meta value for custom field

I have setup a custom meta_key for attachments. Since it is a radio button with Yes/No options, and the default value is always Yes, I need that this default value is saved into the db when the attachment is created.

Right now the problem is that when I upload an image, the Edit Media page shows me that the value for this meta_key is “Yes”, but it is actually not saved in the database until I click “Save All Changes” or “Update Media”.

Read More

Since these attachments can be added both by manually uploading files and automatically by importing an RSS feed, I need the default value to be created at the moment the attachment is created in the db.

UPDATE: To explain the issue in more detail, this is the code I am using in the template to find the attachments. I don’t know if I can modify this to also query the attachments when the _show_attach is null?

$attached_photos = get_children(array(
        'post_parent'    => get_the_ID(),
        'post_type'      => 'attachment',
        'numberposts'    => -1, // show all
        'post_status'    => null,
        'post_mime_type' => 'image',
        'order' => 'ASC',
        'orderby' => 'menu_order',
        'meta_key' => '_show_attach',
        'meta_value' => 'false',
        'meta_compare' => '!='
    ));

Related posts

Leave a Reply

2 comments

  1. You can use add_attachment action to set a default value for a custom field:

    function wpse62481_set_default_meta_value( $attachment_id ) {
        add_post_meta( $attachment_id, '_show_attach', '1' );
    }
    add_action( 'add_attachment', 'wpse62481_set_default_meta_value' );