同时添加自定义图像字段和其他字段 [英] Adding custom image fields and other fields at the same time

查看:24
本文介绍了同时添加自定义图像字段和其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

由于 使用 register_setting()<在 WordPress 2.8 中处理插件选项/code>.

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

我在网上找不到任何简单的干净示例.甚至我发现的 Stack Overflow 上与此相关的问题似乎也没有一个清晰优雅的例子来说明这个工作.

仅供参考;我最初计划使用我已经拥有的插件(Developers Custom Fields)来做到这一点安装,认为使用此插件添加自定义图像字段会非常容易,因为使用它添加文本框非常简单.但是我似乎错了,没有明确的例子来指定这种字段.

如果您知道任何说明添加自定义图像字段(与同时添加其他字段无关)的示例,可以使用原生 WordPress API 代码或与开发人员自定义字段插件集成.

解决方案

你没有完全提到它,但你似乎在处理可重复字段.

感兴趣的两个插件:高级自定义字段自定义内容类型管理器.

今天,我在 WordPress G+ 社区之一中看到了这篇文章:
使用 WordPress3.5 插件内的媒体上传器.

此解决方案最初在此处发布的 SO Question 中已被删除.重写、修订和测试:

ID, 'gallery_data', true );//使用 nonce 进行验证wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_so_14445904');?><div id="dynamic_form"><div id="field_wrap"><?phpif ( 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>图片网址</label><输入类型="文本"class="meta_image_url"名称="画廊[image_url][]"value="<?php esc_html_e( $gallery_data['image_url'][$i]); ?>"/>

<div class="form_field"><label>描述</label><输入类型="文本"class="meta_image_desc"名称="画廊[image_desc][]"value="<?php esc_html_e( $gallery_data['image_desc'][$i]); ?>"/>

<div class="field_right image_wrap"><img src="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>"高度="48" 宽度="48"/>

<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 class="clear"/></div>

<?php}//万一}//endforeach?>

<div style="display:none" id="master-row"><div class="field_row"><div class="field_left"><div class="form_field"><label>图片网址</label><input class="meta_image_url" value="" type="text" name="gallery[image_url][]"/>

<div class="form_field"><label>图片链接</label><input class="meta_image_desc" value="" type="text" name="gallery[image_desc][]"/>

<div class="field_right image_wrap">

<div class="field_right"><input type="button" class="button" value="选择文件" onclick="add_image(this)"/><br/><input class="button" type="button" value="Remove" onclick="remove_field(this)"/>

<div class="clear"></div>

<div id="add_field_row"><input class="button" type="button" value="Add Field" onclick="add_field_row();"/>

<?php}/*** 打印样式和脚本*/函数 print_scripts_so_14445904(){//检查 post_type 是否正确全球 $post;if('post' != $post->post_type )返回;?><style type="text/css">.field_left {向左飘浮;}.field_right {向左飘浮;左边距:10px;}.清除 {清除:两者;}#dynamic_form {宽度:580px;}#dynamic_form 输入[类型=文本] {宽度:300px;}#dynamic_form .field_row {边框:1px 实心 #999;底边距:10px;填充:10px;}#dynamic_form 标签{填充:0 6px;}</风格><script type="text/javascript">函数 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 = 函数(html){var url = jQuery(html).find('img').attr('src');inputField.val(url);jQuery(父).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: '+网址 + '</p>');tb_remove();};返回假;}函数 remove_field(obj) {var parent=jQuery(obj).parent().parent();//console.log(父)parent.remove();}函数 add_field_row() {var row = jQuery('#master-row').html();jQuery(row).appendTo('#field_wrap');}<?php}/*** 保存帖子操作,处理字段*/函数 update_post_gallery_so_14445904( $post_id, $post_object ){//做修改,提前退出**可以去掉**如果(定义('DOING_AUTOSAVE')&& DOING_AUTOSAVE)返回;//正在修改,提前退出if ('revision' == $post_object->post_type)返回;//验证真实性if (!wp_verify_nonce($_POST['noncename_so_14445904'], plugin_basename(__FILE__)))返回;//正确的帖子类型if ( 'post' != $_POST['post_type'] )返回;如果 ( $_POST['gallery'] ){//构建用于保存帖子元数据的数组$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 ];}}如果( $gallery_data )update_post_meta( $post_id, 'gallery_data', $gallery_data );别的delete_post_meta( $post_id, 'gallery_data' );}//没有收到,所有字段都为空,删除选项别的{delete_post_meta( $post_id, 'gallery_data' );}}

结果:

I basically want to have a custom CMS page that has pairs of images and labels for those images defined within it. I intend to use these pairs of items for populating content on a custom page of my new WordPress theme.

I have managed to make a new settings page within the CMS and populate any number of text boxes within it all thanks to Handling Plugins Options in WordPress 2.8 with register_setting().

I just now need to add fields for each text box that let a user open up the media browser and then select an existing image uploaded to WordPress or upload a new one for selection.

I haven't been able to find any simple clean examples of this online. Even the questions related to this on Stack Overflow I found don't seem to have a clear elegant example of this working.

Just for the record; I initially planned to do this with a plugin (Developers Custom Fields) which I already have installed, thinking it would be very easy with this plugin to add custom image fields because it is pretty simple adding text boxes with it. However I seem to be wrong and no clear examples exist for specifying this kind of field.

If you know of any examples that illustrate adding custom image fields (irrelevant of adding other fields at the same time), either using native WordPress API code or integration with the Developers Custom Fields plugin.

解决方案

You don't exactly mention it, but it seems that you are dealing with Repeatable Fields.

Two plugins of interest: Advanced Custom Fields and Custom Content Type Manager.

Today, I've seen this article in one of WordPress communities at G+:
Using the WordPress 3.5 Media Uploader within plugins.

This solution was originally published here in a SO Question that has been deleted since. It is rewritten, revised and tested:

<?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' );
    }
}

Result:

这篇关于同时添加自定义图像字段和其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆