Getting the Featured image URL and inserting it as Custom Field on Post update / publish

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);
        }
}

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)