In this tutorial, I’ll explain to you how to upload multiple featured images in any post type and pages and then show them at the frontend.
We can do this with ACF (Advance custom field) plugin and with custom meta box creation.
Add Meta Box in Post Type and Pages:
add_meta_box() hook used to add a meta box in posts or pages. It gives us a screen to add/edit data and save with post. We just need to pass the specific parameters and run with hook/action.
In this code, we run an action hook
add_meta_boxes and this custom_postpage_meta_box is the callback function to run when add_meta_boxes action hit.
Here we declare the variable
$post_types to hold the array for on which post types should the box appear? You can change the value of this variable as per your need. E.g:-
add_meta_box() this function run the meta box screen in your post type. And you will see another featured image box container. You can change the label of your meta box and can set the position priority like I set in the above code.
Load the field in the meta box:
wp.media. This will allow you to open wp media in the popup and select the featured image which you want to select.
And after this, you will see the box appears in the backend of the post or page.
Save the value of meta box:
We will use
save_post action hook to save the meta box value against the post or page value.
Now, in this function, first we checked that the user has permission to edit that specific post type or not. If it not allowed then it will return the message “You have no permission to edit this post types”. If the user has permission then it will check the
wp_nonce_field() for what data is coming from the same source and verify it. Then it will pass the value to update_post_meta() to save in the database.
After saving the value of the meta box (another featured image) you can access it with this code.
wp_get_attachment_image() this function used for get the image source with html generated. And inside this I used
get_post_meta() function. I think you already know this how to get the post meta with this function. So use this and show on your post where you want.
All code together:
That’s it we learned how to Upload multiple featured images with custom code without any plugin.
Have any query please let me know in the comment box.