【问题标题】:How to add media attachments for the custom post type in wordpress admin panel如何在 wordpress 管理面板中为自定义帖子类型添加媒体附件
【发布时间】:2020-12-09 23:41:03
【问题描述】:

我需要在管理面板中实现功能,以便我可以为特定自定义帖子类型的图库添加图像,我还可以查看/编辑从管理面板上传的所有图像。

P.S 我想在不使用任何插件的情况下在主题中开发此功能。

【问题讨论】:

    标签: wordpress gallery media


    【解决方案1】:

    您可以实现自定义字段,无需任何插件即可调用附件。请参考以下代码:

    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] . '">';
      }
    }
    

    这将在下面的自定义字段中显示附加到帖子的所有图像。

    【讨论】:

      【解决方案2】:

      请看如下:

      • 首先,如果您想在帖子中添加超过 1 张图片,请安装 ACF 插件并创建一个转发器字段,否则您不需要转发器字段。

      如果您想在 ACF 转发器字段的前端将所有帖子显示为画廊,请查看如下:

      <?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; ?>
      

      如果您想显示没有重复字段的图像,请看下面:

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

      【讨论】:

      • 感谢您的回答,但我需要在不使用任何插件的情况下实现它。
      • 好的,@Pratikb.Simform 我将使用自定义功能而不是 ACF 更新我的答案,并让您知道。谢谢
      猜你喜欢
      • 2015-05-07
      • 2015-10-04
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2018-02-23
      • 2018-07-18
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多