【问题标题】:Adding custom image fields and other fields at the same time同时添加自定义图像字段和其他字段
【发布时间】:2013-01-21 19:35:53
【问题描述】:

我基本上想要一个自定义的 CMS 页面,其中包含成对的图像和在其中定义的这些图像的标签。我打算使用这些项目对在我的新 WordPress 主题的自定义页面上填充内容。

感谢Handling Plugins Options in WordPress 2.8 with register_setting(),我设法在 CMS 中创建了一个新的设置页面并在其中填充了任意数量的文本框。

我现在需要为每个文本框添加字段,让用户打开媒体浏览器,然后选择上传到 WordPress 的现有图像或上传新图像以供选择。

我无法在网上找到任何简单干净的示例。甚至我发现的 Stack Overflow 上与此相关的问题似乎也没有一个明确的优雅示例。

仅作记录;我最初计划使用我已经安装的插件 (Developers Custom Fields) 来执行此操作,我认为使用此插件添加自定义图像字段会非常容易,因为使用它添加文本框非常简单。但是我似乎错了,没有明确的例子来指定这种字段。

如果您知道任何说明添加自定义图像字段(与同时添加其他字段无关)的示例,可以使用本机 WordPress API 代码或与 Developers Custom Fields 插件集成。

【问题讨论】:

    标签: wordpress-theming wordpress


    【解决方案1】:

    您没有完全提及它,但似乎您正在处理可重复字段

    两个感兴趣的插件:Advanced Custom FieldsCustom Content Type Manager

    今天,我在 WordPress communities at G+:
    Using the WordPress 3.5 Media Uploader within plugins 之一看到了这篇文章。

    此解决方案最初发布在此处的 SO Question 中,此后已被删除。它被重写、修改和测试:

    <?php
    /**
     * Plugin Name: (SO) Repeatable fields demo
     * Plugin URI:  http://stackoverflow.com/a/14452453/1287812
     * Description: How to make repeatable fields in a meta box
     * Author:      brasofilo
     * License:     GPLv3
     */
    
    add_action( 'admin_init', 'add_post_gallery_so_14445904' );
    add_action( 'admin_head-post.php', 'print_scripts_so_14445904' );
    add_action( 'admin_head-post-new.php', 'print_scripts_so_14445904' );
    add_action( 'save_post', 'update_post_gallery_so_14445904', 10, 2 );
    
    /**
     * Add custom Meta Box to Posts post type
     */
    function add_post_gallery_so_14445904() 
    {
        add_meta_box(
            'post_gallery',
            'Custom Uploader',
            'post_gallery_options_so_14445904',
            'post',
            'normal',
            'core'
        );
    }
    
    /**
     * Print the Meta Box content
     */
    function post_gallery_options_so_14445904() 
    {
        global $post;
        $gallery_data = get_post_meta( $post->ID, 'gallery_data', true );
    
        // Use nonce for verification
        wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_so_14445904' );
    ?>
    
    <div id="dynamic_form">
    
        <div id="field_wrap">
        <?php 
        if ( isset( $gallery_data['image_url'] ) ) 
        {
            for( $i = 0; $i < count( $gallery_data['image_url'] ); $i++ ) 
            {
            ?>
    
            <div class="field_row">
    
              <div class="field_left">
                <div class="form_field">
                  <label>Image URL</label>
                  <input type="text"
                         class="meta_image_url"
                         name="gallery[image_url][]"
                         value="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>"
                  />
                </div>
                <div class="form_field">
                  <label>Description</label>
                  <input type="text"
                         class="meta_image_desc"
                         name="gallery[image_desc][]"
                         value="<?php esc_html_e( $gallery_data['image_desc'][$i] ); ?>"
                  />
                </div>
              </div>
    
              <div class="field_right image_wrap">
                <img src="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>" height="48" width="48" />
              </div>
    
              <div class="field_right">
                <input class="button" type="button" value="Choose File" onclick="add_image(this)" /><br />
                <input class="button" type="button" value="Remove" onclick="remove_field(this)" />
              </div>
    
              <div class="clear" /></div> 
            </div>
            <?php
            } // endif
        } // endforeach
        ?>
        </div>
    
        <div style="display:none" id="master-row">
        <div class="field_row">
            <div class="field_left">
                <div class="form_field">
                    <label>Image URL</label>
                    <input class="meta_image_url" value="" type="text" name="gallery[image_url][]" />
                </div>
                <div class="form_field">
                    <label>Image Link</label>
                    <input class="meta_image_desc" value="" type="text" name="gallery[image_desc][]" />
                </div>
            </div>
            <div class="field_right image_wrap">
            </div> 
            <div class="field_right"> 
                <input type="button" class="button" value="Choose File" onclick="add_image(this)" />
                <br />
                <input class="button" type="button" value="Remove" onclick="remove_field(this)" /> 
            </div>
            <div class="clear"></div>
        </div>
        </div>
    
        <div id="add_field_row">
          <input class="button" type="button" value="Add Field" onclick="add_field_row();" />
        </div>
    
    </div>
    
      <?php
    }
    
    /**
     * Print styles and scripts
     */
    function print_scripts_so_14445904()
    {
        // Check for correct post_type
        global $post;
        if( 'post' != $post->post_type )
            return;
        ?>  
        <style type="text/css">
          .field_left {
            float:left;
          }
    
          .field_right {
            float:left;
            margin-left:10px;
          }
    
          .clear {
            clear:both;
          }
    
          #dynamic_form {
            width:580px;
          }
    
          #dynamic_form input[type=text] {
            width:300px;
          }
    
          #dynamic_form .field_row {
            border:1px solid #999;
            margin-bottom:10px;
            padding:10px;
          }
    
          #dynamic_form label {
            padding:0 6px;
          }
        </style>
    
        <script type="text/javascript">
            function add_image(obj) {
                var parent=jQuery(obj).parent().parent('div.field_row');
                var inputField = jQuery(parent).find("input.meta_image_url");
    
                tb_show('', 'media-upload.php?TB_iframe=true');
    
                window.send_to_editor = function(html) {
                    var url = jQuery(html).find('img').attr('src');
                    inputField.val(url);
                    jQuery(parent)
                    .find("div.image_wrap")
                    .html('<img src="'+url+'" height="48" width="48" />');
    
                    // inputField.closest('p').prev('.awdMetaImage').html('<img height=120 width=120 src="'+url+'"/><p>URL: '+ url + '</p>'); 
    
                    tb_remove();
                };
    
                return false;  
            }
    
            function remove_field(obj) {
                var parent=jQuery(obj).parent().parent();
                //console.log(parent)
                parent.remove();
            }
    
            function add_field_row() {
                var row = jQuery('#master-row').html();
                jQuery(row).appendTo('#field_wrap');
            }
        </script>
        <?php
    }
    
    /**
     * Save post action, process fields
     */
    function update_post_gallery_so_14445904( $post_id, $post_object ) 
    {
        // Doing revision, exit earlier **can be removed**
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )  
            return;
    
        // Doing revision, exit earlier
        if ( 'revision' == $post_object->post_type )
            return;
    
        // Verify authenticity
        if ( !wp_verify_nonce( $_POST['noncename_so_14445904'], plugin_basename( __FILE__ ) ) )
            return;
    
        // Correct post type
        if ( 'post' != $_POST['post_type'] ) 
            return;
    
        if ( $_POST['gallery'] ) 
        {
            // Build array for saving post meta
            $gallery_data = array();
            for ($i = 0; $i < count( $_POST['gallery']['image_url'] ); $i++ ) 
            {
                if ( '' != $_POST['gallery']['image_url'][ $i ] ) 
                {
                    $gallery_data['image_url'][]  = $_POST['gallery']['image_url'][ $i ];
                    $gallery_data['image_desc'][] = $_POST['gallery']['image_desc'][ $i ];
                }
            }
    
            if ( $gallery_data ) 
                update_post_meta( $post_id, 'gallery_data', $gallery_data );
            else 
                delete_post_meta( $post_id, 'gallery_data' );
        } 
        // Nothing received, all fields are empty, delete option
        else 
        {
            delete_post_meta( $post_id, 'gallery_data' );
        }
    }
    

    结果

    【讨论】:

    • 嗨 brasofilo,非常感谢。我需要将此应用到自定义页面,而不是帖子系统 - 因为它需要是一个设置,基本上不是分配给单个帖子的属性。所以我会看看我能从中得到什么。
    • 当点击删除按钮时,图片会从自定义上传器区域中删除,但不会从媒体库中删除。单击“删除”按钮时,如何将图像从媒体库中删除(或从帖子中删除)?
    【解决方案2】:

    对于 Wordpress 3.5,新媒体上传器将打开此脚本更改旧脚本。

    <script type="text/javascript">
        function add_image(obj) {
    
            var parent=jQuery(obj).parent().parent('div.field_row');
            var inputField = jQuery(parent).find("input.meta_image_url");
            var fileFrame = wp.media.frames.file_frame = wp.media({
                multiple: false
            });
            fileFrame.on('select', function() {
                var url = fileFrame.state().get('selection').first().toJSON();
                inputField.val(url.url);
                jQuery(parent)
                .find("div.image_wrap")
                .html('<img src="'+url.url+'" height="48" width="48" />');
            });
            fileFrame.open();
        //});
        };
    
        function reomove_field(obj) {
            var parent=jQuery(obj).parent().parent();
            //console.log(parent)
            parent.remove();
        }
    
        function add_field_row() {
            var row = jQuery('#master-row').html();
            jQuery(row).appendTo('#field_wrap');
        }
    </script>
    

    【讨论】:

    • 请注意,此解决方案将要求您使用 wp_enqueue_media();一个好地方是 add_post_gallery_so_14445904() 里面还有 reomove_field 应该是 remove_field()
    【解决方案3】:

    我在上面使用了@brasofilo 的答案,但是我真的很怀念保存图像ID,所以我可以使用wp_get_attachment_image例如。

    这是我修改后的代码,它还保存了图像 ID。我还使用两个数组来定义元框出现在哪些页面模板和哪些帖子类型上。代码如下:

    <?php
    /**
     * Plugin Name: Repeatable image fields
     * Plugin URI:  https://stackoverflow.com/a/36456957/4800442
     * Description: Repeatable image fields in a meta box.
     * Author:      brasofilo
     * License:     GPLv3
     */
    
    add_action( 'admin_init', 'add_post_gallery_so_14445904' );
    add_action( 'add_meta_boxes_page', 'add_page_gallery_so_14445904' );
    add_action( 'admin_head-post.php', 'print_scripts_so_14445904' );
    add_action( 'admin_head-post-new.php', 'print_scripts_so_14445904' );
    add_action( 'save_post', 'update_post_gallery_so_14445904', 10, 2 );
    
    // Make it work only in selected templates
    $rep_fields_templates = array('page-aboutus.php');
    $rep_fields_posts     = array('service',
                                  'style',
                                  'brand');
    
    /**
     * Add custom Meta Box
     */
    
    // Add meta box to custom posts 
    function add_post_gallery_so_14445904() 
    {
        global $rep_fields_posts;       
        add_meta_box(
            'post_gallery',
            'Slideshow Gallery',
            'post_gallery_options_so_14445904',
            $rep_fields_posts,
            'normal',
            'core'
        );
    }
    
    // Add meta box to custom page templates
    function add_page_gallery_so_14445904() 
    {       
        global $post, $rep_fields_templates;
        if ( in_array( get_post_meta( $post->ID, '_wp_page_template', true ), $rep_fields_templates ) ) {
            add_meta_box(
                'post_gallery',
                'Slideshow Gallery',
                'post_gallery_options_so_14445904',
                'page',
                'normal',
                'core'
            );
        }
    }
    
    /**
     * Print the Meta Box content
     */
    function post_gallery_options_so_14445904() 
    {
        global $post;
        $gallery_data = get_post_meta( $post->ID, 'gallery_data', true );
    
        // Use nonce for verification
        wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_so_14445904' );
        ?>
    
        <div id="dynamic_form">
    
            <div id="field_wrap">
            <?php 
            if ( isset( $gallery_data['image_url'] ) ) 
            {
                for( $i = 0; $i < count( $gallery_data['image_url'] ); $i++ ) 
                {
                ?>
    
                <div class="field_row">
    
                  <div class="field_left">
                    <div class="form_field">
                      <!--<label>Image URL</label>-->
                      <input type="hidden"
                             class="meta_image_url"
                             name="gallery[image_url][]"
                             value="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>"
                      />
                      <input type="hidden"
                             class="meta_image_id"
                             name="gallery[image_id][]"
                             value="<?php esc_html_e( $gallery_data['image_id'][$i] ); ?>"
                      />
                    </div>
                    <div class="form_field" style="margin-bottom: 20px">
                      <label>Description</label>
                      <textarea
                             class="meta_image_desc"
                             name="gallery[image_desc][]"
                             rows="3"
                             style="width: 100%"><?php esc_html_e( $gallery_data['image_desc'][$i] ); ?></textarea>
                    </div>
                    <input class="button" type="button" value="Choose File" onclick="add_image(this)" />&nbsp;&nbsp;&nbsp;
                    <input class="button" type="button" value="Remove" onclick="remove_field(this)" />
                  </div>
    
                  <div class="field_right image_wrap">
                    <img src="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>" />
                  </div>
                  <div class="clear" /></div> 
                </div>
                <?php
                } // endif
            } // endforeach
            ?>
            </div>
    
            <div style="display:none" id="master-row">
            <div class="field_row">
                <div class="field_left">
                    <div class="form_field">
                        <!--<label>Image URL</label>-->
                        <input class="meta_image_url" value=""  name="gallery[image_url][]" />
                        <input class="meta_image_id" value=""  name="gallery[image_id][]" />
                    </div>
                    <div class="form_field" style="margin-bottom: 20px">
                        <label>Description</label>
                        <textarea class="meta_image_desc" name="gallery[image_desc][]" rows="3" style="width: 100%"></textarea>
                    </div>
                    <input type="button" class="button" value="Choose Image" onclick="add_image(this)" />&nbsp;&nbsp;&nbsp;
                    <input class="button" type="button" value="Remove" onclick="remove_field(this)" />
                </div>
                <div class="field_right image_wrap">
                </div>
                <div class="clear"></div>
            </div>
            </div>
    
            <div id="add_field_row">
              <input class="button" type="button" value="Add Image" onclick="add_field_row();" />
            </div>
            <?php if ( 'trend' == get_post_type( $post->ID ) ) { ?>
            <p style="color: #a00;">Make sure the number if images you add is a <b>multiple of 5</b>.</p>
            <?php } ?>
        </div>
        <?php
    }
    
    /**
     * Print styles and scripts
     */
    function print_scripts_so_14445904()
    {
        // Check for correct post_type
        global $post, $rep_fields_templates, $rep_fields_posts;
        if ( !in_array( get_post_meta( $post->ID, '_wp_page_template', true ), $rep_fields_templates ) && 
             !in_array( get_post_type( $post->ID)                           , $rep_fields_posts ) )
            return;
        ?>  
        <style type="text/css">
          .field_left {
            float:left;
            width: 75%;
            padding-right: 20px;
            box-sizing:border-box;  
          }
          .field_right {
            float:left;
            width: 25%;
          }
          .image_wrap img {
              max-width: 100%;
          }
          #dynamic_form input[type=text] {
            width:100%;
          }
          #dynamic_form .field_row {
            border:1px solid #cecece;
            margin-bottom:10px;
            padding:10px;
          }
          #dynamic_form label {
            display: block;
            margin-bottom: 5px;
          }
        </style>
    
        <script type="text/javascript">
            function add_image(obj) {
    
                var parent=jQuery(obj).parent().parent('div.field_row');
                var inputField = jQuery(parent).find("input.meta_image_url");
                var inputFieldID = jQuery(parent).find("input.meta_image_id");
                var fileFrame = wp.media.frames.file_frame = wp.media({
                    multiple: false
                });
                fileFrame.on('select', function() {
                    var selection = fileFrame.state().get('selection').first().toJSON();
                    inputField.val(selection.url);
                    inputFieldID.val(selection.id);
                    jQuery(parent)
                    .find("div.image_wrap")
                    .html('<img src="'+selection.url+'" />');
                });
                fileFrame.open();
            //});
            };
    
            function remove_field(obj) {
                var parent=jQuery(obj).parent().parent();
                parent.remove();
            }
    
            function add_field_row() {
                var row = jQuery('#master-row').html();
                jQuery(row).appendTo('#field_wrap');
            }
        </script>
        <?php
    }
    
    /**
     * Save post action, process fields
     */
    function update_post_gallery_so_14445904( $post_id, $post_object ) 
    {
        // Doing revision, exit earlier **can be removed**
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )  
            return;
    
        // Doing revision, exit earlier
        if ( 'revision' == $post_object->post_type )
            return;
    
        // Verify authenticity
        if ( !wp_verify_nonce( $_POST['noncename_so_14445904'], plugin_basename( __FILE__ ) ) )
            return;
    
        global $rep_fields_templates, $rep_fields_posts;
        if ( !in_array( get_post_meta( $post_id, '_wp_page_template', true ), $rep_fields_templates ) && 
             !in_array( get_post_type( $post_id)                            , $rep_fields_posts ) ) 
            return;
    
        if ( $_POST['gallery'] ) 
        {
            // Build array for saving post meta
            $gallery_data = array();
            for ($i = 0; $i < count( $_POST['gallery']['image_url'] ); $i++ ) 
            {
                if ( '' != $_POST['gallery']['image_url'][ $i ] ) 
                {
                    $gallery_data['image_url'][]  = $_POST['gallery']['image_url'][ $i ];
                    $gallery_data['image_id'][]  = $_POST['gallery']['image_id'][ $i ];
                    $gallery_data['image_desc'][] = $_POST['gallery']['image_desc'][ $i ];
                }
            }
    
            if ( $gallery_data ) 
                update_post_meta( $post_id, 'gallery_data', $gallery_data );
            else 
                delete_post_meta( $post_id, 'gallery_data' );
        } 
        // Nothing received, all fields are empty, delete option
        else 
        {
            delete_post_meta( $post_id, 'gallery_data' );
        }
    }
    

    以下是如何将数据输出到主题的示例。

    <?php 
    if ( '' != get_post_meta( get_the_ID(), 'gallery_data', true ) ) { $gallery = get_post_meta( get_the_ID(), 'gallery_data', true ); }
    
    if ( isset( $gallery['image_id'] ) ) :
    
        for( $i = 0; $i < count( $gallery['image_id'] ); $i++ ) { 
            if ( '' != $gallery['image_id'][$i] ) {
                echo wp_get_attachment_image( $gallery['image_id'][$i], 'gallery_large' );
                if ( isset($gallery['image_desc'][$i]) ) echo $gallery['image_desc'][$i];
            }   
        }
    
    endif; 
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多