Search code examples
wordpressgallerymedia

How to add media attachments for the custom post type in wordpress admin panel


I need to implement functionality in the admin Panel in such a way that I can add images for the gallery of particular custom post type also I would be able to view/edit the all the images uploaded from the admin panel.

P.S I want to develop this functionality in the theme without using any plugins.


Solution

  • You can implement the custom field into which you can call the attachments without any plugin. Please refer to the below code:

    add_action('admin_init', 'show_custom_post_images');
    
    function show_custom_post_images() {
      add_meta_box(
        'Pictures ',
        __('Images attached to post ', 'domain'),
        'post_image',
        'post_type',
        'normal',
        'default'
      );
    }
    
    function post_image() {
      global $post;
      $arguments = array(
        'numberposts' => - 1,
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'post_parent' => $post->ID,
        'post_status' => null,
        'exclude' => get_post_thumbnail_id() ,
        'orderby' => 'menu_order',
        'order' => 'ASC'
      );
      $post_attachments = get_posts($arguments);
      foreach ($post_attachments as $attachment) {
        $preview = wp_get_attachment_image_src(
          $attachment->ID, 'wpestate_slider_thumb'
        );
        echo '<img src="' . $preview[0] . '">';
      }
    }
    

    This will show all the images attached to the post in a custom field below.