Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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);
}
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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);
        }
}
share|improve this answer
    
Thanks for the answer - apologies for taking so long to get back to you. Got side-tracked on a few other urgent projects :) –  Gheko Dec 11 '12 at 11:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.