Getting the Featured image URL and inserting it as Custom Field on Post update / publish
I've tried a number of solutions posted here regarding converting custom fields to featured images - of course in reverse; but non seem to work for me.
What I'm trying to do is grab the Featured Image URL once the image is uploaded and set as a featured image; then automatically set the full size image URL as a custom field. This needs to work on both post Update for existing articles that do not currently have the custom field set and for post Publish for new articles.
As mentioned I have tried numerous suggestions based on this but none seem to work. Here is the last bit of code that I attempted without success though - and the frustrating part is that I cannot seem to debug or get any errors out of this:
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
$post_thumbnail_id = get_post_thumbnail_id();
$post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);
add_post_meta($post_ID, 'lead_image', $post_thumbnail_url, false);
}
Solutions
The function
get_post_thumbnail_id()
needs a value to be passed if using outside the wordpress loop. You forgot to pass it.
The code you're using will create a new
custom field
on each update so here's the modified code that'll perform
update_post_meta
function if that meta_key is already present in database.
The bellow code is tested on WordPress 3.4.1 with Twenty Ten theme installed
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
global $wpdb;
$post_thumbnail_id = get_post_thumbnail_id( $post_ID );
$post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);
//to make sure if we already has set the value
$has_image = get_post_meta($post_ID, 'lead_image', true);
//will update instead of add if meta_key has value.
if ($has_image != '') {
add_post_meta($post_ID, 'lead_image', $post_thumbnail_url, true);
} else {
update_post_meta($post_ID, 'lead_image', $post_thumbnail_url, $has_image);
}
}