I am creating a small plugin to add a 'data-pin-description' attribute to my images. I intend for the client to be able to add that meta data description to any image attachment from admin and then have that meta value be output to the tag on the front end, when the attachment is added to post content. I want the plugin to grab that meta data at the appropriate time and include it with the img tag data- attribute and value, before it's already output. End result should be:
My admin code seems to be accepting and saving the client-entered value just find, however I am having trouble outputting that data. One problem is I have been unable to identify which hook would retrieve and add that data to the tag at the correct time
I've tried querying the attachment posts but I don't know what action or filter to hook into
Here is how I'm adding the meta data in admin:
<?php
//exit if file is called directly
if (! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Adding a custom field to Attachment Edit Fields
* @param array $form_fields
* @param WP_POST $post
* @return array
*/
//add attachment fields
function ad_add_pinterest_fields( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'pin-description', true );
$form_fields['pin-description'] = array(
'value' => $field_value ? esc_textarea($field_value) : '',
'label' => __( 'Pin Description' ),
'helps' => __( 'Add a short description for Pinterest SEO' ),
'input' => 'textarea'
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'ad_add_pinterest_fields', null, 2 );
//save attachment fields
function ad_save_pinterest_fields( $attachment_id ) {
if ( isset( $_REQUEST['attachments'][$attachment_id]['pin-description'] ) ) {
$pinDescription = sanitize_text_field( $_REQUEST['attachments'][$attachment_id]['pin-description'] );
update_post_meta( $attachment_id, 'pin-description', $pinDescription );
}
}
add_action( 'edit_attachment', 'ad_save_pinterest_fields' );
?>
I expect to retrieve the post_meta of each attachment image for a given post, but have only received errors