Pratikb.Simform
Pratikb.Simform

Reputation: 61

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.

Upvotes: 3

Views: 4113

Answers (2)

Pratik Bhatt
Pratik Bhatt

Reputation: 488

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.

Upvotes: 2

Govind Soni
Govind Soni

Reputation: 313

Please have a look as below:

  • First of all, install the ACF plugin and create a repeater field if you want to add more than 1 image to a post else you no need repeater field.

If you want to display all post iamges as gallery on fronend from ACF repeater field, Plesae have a look as below:

<?php if( have_rows('repeater_field_name') ): ?>
 <ul class="slides">
   <?php
     while( have_rows('repeater_field_name') ): the_row();
     $image = get_sub_field('image');
   ?>
      <li class="slide">
        <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
      </li>
   <?php endwhile; ?>
  </ul>
<?php endif; ?>

If you want to show the image without repeater field, Please have a look below:

<?php
  $image = get_field('instructor-image');
  if( !empty($image) ):
?>
    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>

Upvotes: 1

Related Questions