0

I got a function that automatically creates a custom field in the post. I have this located in my functions.php.

Image is the name of the custom field and HERE is the value. How can I put the function w_thumbnail_src as the variable?

add_action('wp_insert_post', 'mk_set_default_custom_fields');
    function mk_set_default_custom_fields($post_id)

    {
        if ( $_GET['post_type'] != 'post' ) {
            add_post_meta($post_id, 'Image','HERE', true);
        }
        return true;
    }

And let me add that w_thumbnail_src is a function in the same file that looks like this

function w_thumbnail_src() {
    if (has_post_thumbnail()) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis');
       echo $thumb[0]; // thumbnail url
    }
}

EDIT : Here is the final code that adds the thumbnail url to a custom field named Image.

function w_thumbnail_src() {
    if (has_post_thumbnail()) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis');
        return $thumb[0]; // thumbnail url
    } else {
        return '';  // or a default thumbnail url
    }
}


add_action('publish_page', 'add_custom_field_automatically', 'w_thumbnail_src');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_id) {
global $wpdb;
if(!wp_is_post_revision($post_id)) {
add_post_meta($post_id, 'Image', w_thumbnail_src(), true);
}
}
1
  • try to change your function to return the result, not echo it.
    – Michael
    Feb 5, 2012 at 22:05

1 Answer 1

1

You can just update your function to pass the post_id as a parameter.

function w_thumbnail_src($post_id) {
    if (has_post_thumbnail($post_id)) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'emphasis');
       echo $thumb[0]; // thumbnail url
    }
}
1
  • didnt work but I got the solution. Just aint got reputation ebough to answer my own questono before in 3 hours :) Anyways, thanks for the try!
    – Demilio
    Feb 5, 2012 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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