Why does Wordpress featured image not save when I publish my post?
I inherited this website from another developer. We recently updated the Advanced Custom Fields PRO plugin to fix a different issue and it was working fine. I got a call this morning that the featured image appears when being added to the post, but when they publish it the featured image disappears.
I've checked to make sure that featured images are allowed. Existing posts display the featured image, but editing or adding new posts and then publishing does not attach the image to the post.
I've looked at the save_post hook methods and they don't touch the featured image at all.
Any ideas?
Here's the method added via the 'save_post' hook:
function save_listing($listing_id, $post) {
global $wpdb;
if ('listings' != $post->post_type)
return;
//store fullDescription, keywords and categories in wp_listings
$full_description = get_field('listing_full_description', $listing_id);
$keywords = get_field('listing_keywords', $listing_id);
$terms = wp_get_post_terms($listing_id, 'listing-categories', ['fields' => 'names']);
$categories = implode(", ", $terms);
$tier = get_field('listing_tier', $listing_id);
$tier = array_search($tier, ['standard', 'premium', 'platinum']) + 1;
$wpdb->replace('wp_listings', ['id' => $listing_id, 'title' => $post->post_title, 'fullDescription' => $full_description, 'keywords' => $keywords, 'categories' => $categories, 'tier' => $tier], ['%d', '%s', '%s', '%s', '%s', '%d']);
$locations = get_field('listing_locations', $listing_id);
$wpdb->delete('wp_locations', ['listing_id' => $listing_id], ['%d']);
if (!isset($locations))
return;
if ($post->post_status != 'publish')
return;
foreach ($locations as $loc_number => $location) {
$disabled = isset($location['disable_map_location']) && $location['disable_map_location'] ? 1 : 0;
$wpdb->insert('wp_locations', ['listing_id' => $listing_id, 'loc_number' => $loc_number, 'lat' => $location['map']['lat'], 'lng' => $location['map']['lng'],
'zip' => $location['zip'], 'city' => $location['city'], 'state' => $location['state'], 'disabled' => $disabled], ['%d', '%d', '%f', '%f', '%s', '%s', '%s', '%d']);
}
}
add_action('save_post', 'save_listing', 100000000, 2);
Also verified that featured images are supported
if (function_exists('add_theme_support')) {
add_theme_support('post-thumbnails'); }
I have verified that on post save the post meta data includes "_thumbnail_id" and there is a post attachment corresponding with that ID. However when the page reloads there is no Featured Image.
Solutions
So after looking at the $_POST after saving and then cross-referencing the post meta data I found that the _thumbnail_id was not getting saved in the meta data. Still not sure why, but I fixed it by adding this code to my save_post hook method:
update_post_meta($post->ID, '_thumbnail_id', filter_input(INPUT_POST, '_thumbnail_id') );
This feels a bit hacky but the whole site is hacky :)