0

This seems like it should be fairly simple, but I'm drawing a blank on it:

Have a checkbox in the media uploader and media manager that, when checked, adds a CSS class name to the image. It should stay checked.

The kicker is I can't use post meta to store the checked or not checked status. It's a long story, but basically the requirements of the project I'm working on say that setting a global meta key/value on the image is not OK.

I figured out how to add the checkbox and set/unset post meta with it:

/**
 * Add a checkbox to media uploader & manager to mark an image as a Profile Image
 *
 */

function my_select_profile_image( $form_fields, $post ) {
   $is_profile_image = (bool) get_post_meta($post->ID, '_is_profile_image', true);
   $checked = ($is_profile_image) ? 'checked' : '';

    $form_fields['is_profile_image'] = array(
    'label' => 'Profile Image?',
    'input' => 'html',
    'html' => "<input type='checkbox' name='attachments[{$post->ID}][is_profile_image]' id='attachments[{$post->ID}][is_profile_image]' {$checked} />",
   'value' => $is_profile_image,
    'helps' => 'Checking this box will add profile image styling to the image & caption.'
    );
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'my_select_profile_image', null, 2 );

/**
 * Update image meta based on Profile Image checkbox status
 *
 *
 */
function my_save_profile_image($post, $attachment) {
    if( isset( $attachment['is_profile_image'] ) )
        update_post_meta( $post['ID'], '_is_profile_image', true );

    if( !isset( $attachment['is_profile_image'] ) )
        update_post_meta( $post['ID'], '_is_profile_image', false );
    return $post;
}
add_filter( 'attachment_fields_to_save', 'my_save_profile_image', null, 2 )

But with post meta off the table, I'm at a loss on how to do this.

1 Answer 1

0

Given this

I can't use post meta

I suppose this is a typo (my emphasis)

setting a global meta key/value on the image is not OK

It's either a post meta or a site option.
To use it as site option, use this in attachments_fields_to_edit:

$is_profile_image = get_option( '_is_profile_image' );
$checked = isset( $is_profile_image[ $post->ID ] ) ? 'checked' : '';

And this on attachment_fields_to_save:

function my_save_profile_image($post, $attachment) 
{
    $is_profile_image = get_option( '_is_profile_image' );
    if( isset( $attachment['is_profile_image'] ) )
        $is_profile_image[ $post['ID'] ] = true;
    else 
        unset( $is_profile_image[ $post['ID'] ] );

    update_option( '_is_profile_image', $is_profile_image );
    return $post;
}

The site option _is_profile_image will be an array like:

array (size=2)
  96 => boolean true
  97 => boolean true

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.