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".

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' => '!='

2 Answers 2


Why not cover this in your query and use isNull() ? When your meta_key is null for this attachment it is true.

  • I would, but I do not know how - please see the updated question for the code I am using. I don't know if there is a way for me to also query for attachments that _show_attach is null (or to be exact, it is missing altogether) in the same query.
    – ragulka
    Commented Aug 21, 2012 at 8:28
  • you can always use wpdb to make complex queries codex.wordpress.org/Class_Reference/wpdb
    – woony
    Commented Aug 21, 2012 at 8:46

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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.