Tell us what you are trying to do?
Adding a post form when a user uploads one or multiple images, the first image is selected and is added to the featured image. I have gotten the code to work on a variety of other aspects but the featured image eludes me. Seems like it should work so I don't know what I am missing.
The code is actually working. The problem is that you will need to use the AJAX upload for the function to work. The main reason is because when the function is triggered, the images have not yet been uploaded.
So I would recommend using the wordpress media library uploader for the function to work.
Thanks for the info so far. Unfortunately, this is a public page so using the media library isn't an option.
Since it is a public function I am logging posts as pending rather than published. What if I add a function on post status change pending -> publish. In that function I would grab the first image uploaded in that custom field and update the featured image. But, I would only update the featured image if one does not exist and also if an image does exist in the custom field. I think that could work as an alternative work around since at that point the image would exist in the media library and be attached to the post.
This is what I got so far. Not sure what I am missing.
do_action('pending_to_publish', 'update_featured_image');
function update_featured_image($post_id){
global $post;
global $wpdb;
if (($post->post_type=='observations') && (!has_post_thumbnail($post_id)) ){
$images = get_post_field( 'wpcf-snowpack-photos', $post_id );
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $images ));
set_post_thumbnail($post_id, attachment_url_to_postid($attachment[0]));
}
}
Case closed in case somebody wants to go this direction for some reason:
add_action('pending_to_publish', 'update_featured_image',10 ,3);
function update_featured_image($post_id){
global $post;
global $wpdb;
if (($post->post_type=='observations') && (!has_post_thumbnail($post_id)) ){
$images = get_post_field( 'wpcf-snowpack-photos', $post_id );
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $images ));
set_post_thumbnail($post_id, $attachment[0]);
}
}