How do I Add images uploaded in the post to a default custom field

I’m trying to add the URL of the post images in to a default custom field. Here is the code I got so far…

Here is how I add the default custom field:

Read More
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', '', true);
        }
        return true;
    }

Now I need a function that fills the value with the URL from the image uploaded. If there is no image uploaded the field can be empty.

Here is the code to fill the value with info, but I need the thumbnail url in the value

add_post_meta($post_id, 'custom field name', 'custom field value', true);

Related posts

Leave a Reply

1 comment

  1. Can you explain why you need a custom field for the image ? if there is no special reason for that , you should use the_post_thumbnail() function that is built in wordpress and will not have you mess with custom fields.

    You can read more here :

    Display thumbnail from custom field

    EDIT
    Well, if you insist on using it :

    add_action('wp_insert_post', 'mk_set_default_custom_fields');
        function mk_set_default_custom_fields($post_id)
        {
            if ( $_GET['post_type'] != 'post' ) {
            $image1 = wp_get_attachment_image_src(get_post_thumbnail_id()) ;
                update_post_meta($post_id, 'image', $image1[0],true);
            }
            return true;
        }
    

    Of course the feature image needs o be defined (or set a default) , and you can choose the sizes in the get_post_thumbnail() function.