1

i have a custom dropdown field on post and i would to get the value from that custom field and insert it on each image caption field uploaded to the current post.

I have been looking for a way to do this and found a couple of examples but not even one work. This morning i found a Wordpress filter that is called attachment_fields_to_save. To my surprise on the codex was an example of almost the same thing i was looking for but i didn't work.

This is the code

function insert_custom_default_caption($post, $attachment) {
if ( substr($post['post_mime_type'], 0, 5) == 'image' ) {
    if ( strlen(trim($post['post_title'])) == 0 ) {
        $post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid']));
        $post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.');
    }

    // captions are saved as the post_excerpt, so we check for it before overwriting
    // if no captions were provided by the user, we fill it with our default
    if ( strlen(trim($post['post_excerpt'])) == 0 ) {
        $post['post_excerpt'] = 'default caption';
    }
}

return $post . $attachment;
}

add_filter('attachment_fields_to_save', 'insert_custom_default_caption', 10, 2);

Can anyone help me to see what is wrong with that code?

1 Answer 1

2

In the filter, you will need to find the post parent of $post, get the value of the custom field of parent post and then add that value to $post['post_excerpt'] (where the caption is stored):

add_filter('attachment_fields_to_save', 'wpse_insert_custom_caption', 10, 2);
function insert_custom_default_caption($post, $attachment) {

    //Check if the $post is attached to a parent post
    if( $post->post_parent ) {
        //Custom field of the attachment's parent post
        $custom_caption = get_post_meta( $post->post_parent, 'parent_custom_field', true );

        //captions are saved as the post_excerpt
        if ( !empty $custom_caption ) ) {
            $previous_caption = $post['post_excerpt'];
            $post['post_excerpt'] = $previous_caption.$custom_caption;
        }

    }

    return $post;
}

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.