{"id":102,"date":"2024-03-28T22:46:00","date_gmt":"2024-03-28T22:46:00","guid":{"rendered":"https:\/\/www.kwwd.co.uk\/blog\/?p=102"},"modified":"2024-03-28T22:46:00","modified_gmt":"2024-03-28T22:46:00","slug":"add-custom-image-thumbnail-upload-metabox-to-wordpress","status":"publish","type":"post","link":"https:\/\/www.kwwd.co.uk\/blog\/add-custom-image-thumbnail-upload-metabox-to-wordpress\/","title":{"rendered":"Add Custom Image &#038; Thumbnail Upload MetaBox To WordPress"},"content":{"rendered":"<p>This creates a custom metabox for posts and pages and allows us to upload an image. Copy it into your child theme&#8217;s functions.php file<\/p>\n<p>NOTE: This is will generate thumbnails as set by your theme&#8217;s code when uploading your main image<\/p>\n<pre><code class=\"language-php line-numbers\">\r\n&lt;?php\r\n\/********************************************************\r\n ** 28-03-2024: Add Custom Pinterest Image\r\n *******************************************************\/\r\n function custom_pinterest_image_metabox() {\r\n    add_meta_box(\r\n        'custom_pinterest_image_metabox',\r\n        'Custom Pinterest Image',\r\n        'render_custom_pinterest_image_metabox',\r\n        array('post', 'page'),\r\n        'normal',\r\n        'high'\r\n    );\r\n}\r\nadd_action('add_meta_boxes', 'custom_pinterest_image_metabox');\r\n\r\nfunction render_custom_pinterest_image_metabox($post) {\r\n    \/\/ Add nonce for security and authentication.\r\n    wp_nonce_field('custom_pinterest_image_metabox_nonce', 'custom_pinterest_image_metabox_nonce');\r\n\r\n    \/\/ Get the existing meta value (if any).\r\n    $image_id = get_post_meta($post-&gt;ID, 'custom_pinterest_image_id', true);\r\n    $image_url = wp_get_attachment_url($image_id);\r\n\t\r\n\t\r\n\t$thumbnail_url = wp_get_attachment_image_src( $image_id, 'thumbnail' ); \/\/ Replace 'thumbnail' with your desired size\r\n\tif ( $thumbnail_url ) {\r\n\t  $thumbnail_url = $thumbnail_url[0]; \/\/ Access the actual image URL from the array\r\n\t}\r\n    ?&gt;\r\n    &lt;p&gt;\r\n        &lt;label for=\"custom_pinterest_image_upload\"&gt;&lt;?php _e('Upload Image'); ?&gt;&lt;\/label&gt;\r\n        &lt;input type=\"button\" id=\"custom_pinterest_image_upload_button\" class=\"button\" value=\"&lt;?php _e('Upload Image'); ?&gt;\" \/&gt;\r\n        &lt;input type=\"hidden\" id=\"custom_pinterest_image_id\" name=\"custom_pinterest_image_id\" value=\"&lt;?php echo esc_attr($image_id); ?&gt;\" \/&gt;\r\n        &lt;br \/&gt;\r\n        &lt;!--&lt;img id=\"custom_pinterest_image\" src=\"&lt;?php\/\/echo esc_attr($image_url); ?&gt;\" style=\"max-width:100%;\" \/&gt;--&gt;\r\n\t\t&lt;?php\r\n\t\tif($thumbnail_url)\r\n\t\t{\r\n\t\t?&gt;\t\t\t\r\n\t\t&lt;img id=\"custom_pinterest_image\" src=\"&lt;?php echo esc_attr($thumbnail_url); ?&gt;\" \/&gt;\r\n\t\t&lt;?php\r\n\t\t}\r\n\t\t?&gt;\r\n    &lt;\/p&gt;\r\n    &lt;?php\r\n}\r\n\r\nfunction save_custom_pinterest_image_metabox($post_id) {\r\n    \/\/ Check if our nonce is set.\r\n    if (!isset($_POST['custom_pinterest_image_metabox_nonce'])) {\r\n        return;\r\n    }\r\n\r\n    \/\/ Verify that the nonce is valid.\r\n    if (!wp_verify_nonce($_POST['custom_pinterest_image_metabox_nonce'], 'custom_pinterest_image_metabox_nonce')) {\r\n        return;\r\n    }\r\n\r\n    \/\/ If this is an autosave, our form has not been submitted, so we don't want to do anything.\r\n    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\r\n        return;\r\n    }\r\n\r\n    \/\/ Check the user's permissions.\r\n    if ('page' === $_POST['post_type']) {\r\n        if (!current_user_can('edit_page', $post_id)) {\r\n            return;\r\n        }\r\n    } else {\r\n        if (!current_user_can('edit_post', $post_id)) {\r\n            return;\r\n        }\r\n    }\r\n\r\n    \/\/ Make sure that it is set.\r\n    if (!isset($_POST['custom_pinterest_image_id'])) {\r\n        return;\r\n    }\r\n\r\n    \/\/ Sanitize user input.\r\n    $image_id = sanitize_text_field($_POST['custom_pinterest_image_id']);\r\n\r\n    \/\/ Update the meta field.\r\n    update_post_meta($post_id, 'custom_pinterest_image_id', $image_id);\r\n\r\n    \/\/ Generate thumbnails.\r\n    if ($image_id) {\r\n        $metadata = wp_generate_attachment_metadata($image_id, get_attached_file($image_id));\r\n        wp_update_attachment_metadata($image_id, $metadata);\r\n    }\r\n}\r\nadd_action('save_post', 'save_custom_pinterest_image_metabox');\r\n\r\n\r\n\r\n\/** ENQUEUE ADMIN JS **\/\r\n\r\n\/\/ get_stylesheet_directory_uri() = Child Theme Usage\r\n\/\/ get_template_directory_uri() = Parent Theme Usage\r\n\r\nfunction custom_pinterest_image_upload_enqueue_script() {\r\n    wp_enqueue_script('custom-image-upload', get_stylesheet_directory_uri() . '\/js\/adminscripts.js', array('jquery'), null, true);\r\n}\r\nadd_action('admin_enqueue_scripts', 'custom_pinterest_image_upload_enqueue_script');\r\n<\/code><\/pre>\n<p>We also need to add some JavaScript in order to interact with the WordPress Media Uploader. This script (not amending the code above) should be placed in a folder called &#8220;js&#8221; and the file named &#8220;adminscripts.js&#8221;.<\/p>\n<pre><code class=\"language-javascript line-numbers\">\r\njQuery(document).ready(function($){\r\n    \/\/ Instantiates the variable that holds the media library frame.\r\n    var custom_pinterest_image_frame;\r\n    \r\n    \/\/ Runs when the image upload button is clicked.\r\n    $('#custom_pinterest_image_upload_button').click(function(e) {\r\n        e.preventDefault();\r\n        \r\n        \/\/ If the frame already exists, reopen it.\r\n        if (custom_pinterest_image_frame) {\r\n            custom_pinterest_image_frame.open();\r\n            return;\r\n        }\r\n        \r\n        \/\/ Sets up the media library frame.\r\n        custom_pinterest_image_frame = wp.media.frames.customHeader = wp.media({\r\n            title: 'Choose Image',\r\n            button: { text: 'Choose Image' },\r\n            multiple: false\r\n        });\r\n        \r\n        \/\/ Runs when an image is selected.\r\n        custom_pinterest_image_frame.on('select', function() {\r\n            var attachment = custom_pinterest_image_frame.state().get('selection').first().toJSON();\r\n            $('#custom_pinterest_image_id').val(attachment.id);\r\n            $('#custom_pinterest_image').attr('src', attachment.url);\r\n        });\r\n        \r\n        \/\/ Opens the media library frame.\r\n        custom_pinterest_image_frame.open();\r\n    });\r\n});\r\n\r\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>This creates a custom metabox for posts and pages and allows us to upload an image. Copy it into your child theme&#8217;s functions.php file NOTE: [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[26],"class_list":["post-102","post","type-post","status-publish","format-standard","hentry","category-wordpress","tag-images"],"_links":{"self":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts\/102","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=102"}],"version-history":[{"count":0,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts\/102\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=102"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=102"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=102"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}