Hello,
First things first - Gravity Forms is amazing. Taking a look at the code under the hood... Me Gusta!
And on to my issue...
I am trying to populate a custom field's value with the attachment id generated by a separate post image field. I'm figuring I'll need to do something with functions fired on the gform_post_submission or gform_post_data hooks, but I'm really not sure how to get at the attachment ids properly.
Here is what I have now. It sort of gets the job done, but it's also pretty fragile due to the way that I'm determining the attachment IDs.
<?php
add_action( "gform_post_submission", "post_submission_handler" );
function post_submission_handler( $entry ){
// Hacky way of determining attachment id
#update_post_meta( $entry['post_id'], 'my_meta_key', $entry['post_id'] + 1);
// Less hacky, but still hacky way of determining the attachment id.
$meta_key = 'my_meta_key';
$attachment_index = 0; // 0 indexed. For example, GF post image field 1 will be the first attachment.
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $entry['post_id'],
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);
$attachments = get_posts( $args );
if ( $attachments ) {
$counter = 0;
foreach ( $attachments as $attachment ) {
if ( $counter == $attachment_index ) {
update_post_meta( $entry['post_id'], $meta_key, $attachment->ID );
break;
}
}
}
return $entry;
}
I also toyed around with this idea, but it won't work because the GF image url is not the same as a post guid (not that this is a good approach to begin with, but at this point, I'm trying to just make it work.)
<?php
add_filter("gform_post_data", "gfcustom_set_pattern_post_type", 10, 2);
function gfcustom_set_pattern_post_type($post_data, $form){
global $wpdb;
$image_url = $post_data['images'][0]['url']; // this is not a guid though... (not to mention the 0 index approach being weak)
// ...so this will not work:
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE guid = '$image_url'" ) );
$post_data['post_custom_fields']['my_custom_field'] = $thepost->ID;
return $post_data;
}
-goto10 (via wilson)