eTatvaSoft is a leading India based digital agency providing custom PHP solutions, Ecommerce development, mobile development, web designing and branding services to clients around the world
PHP Development Services in India
Date published: 08/03/2016
4.5 / 5 stars

To misinterpret a WordPress site as just a blogging platform is a common mistake occurred amongst a number of users, but it was mere past stories. With the major advancements in WordPress, now it is more into versatile Content Management System (CMS), rather than just being blogging. Top brands like Time Magazine, Google, Facebook, Sony, Disney, LinkedIn, The New York Times, CNN, eBay, and much more too have their websites developed in WordPress and the main reason for them to adapt WordPress is its robust feature.

Other functionalities can be added upon by various themes and plugins and even some of them can be customized according to the needs. Like Custom code for adding Image repeater.

image repeater

Many plugins are available to accomplish this task, but there are few drawbacks in them like few fields automatically vanish or adding two fields with same name block the site, which at times can create a huge blunder. Lets more forth, to customize image repeater in WordPress and add a repeater for images on your WordPress Admin screen.

PHP Code

Add below code into functions.php of your active theme. Function “add_image_slider_meta_box” will be called when a user accesses the admin area.

// Add custom meta box for Image slider
add_action('admin_init', 'add_image_slider_meta_box');

Add below code to functions.php. Now, the question arises, why to add-on?

It adds meta box to Admin (Page screen) with meta box id “image_sliderId” and title “Top Image Slider Box” and the callback function “add_image_slider()”.

function add_image_slider_meta_box() {
    add_meta_box('image_sliderId', 'Top Image Slider Box', 'add_image_slider', 'page', 'normal', 'high');
}

Add below mentioned code to functions.php. This is our callback function “add_image_slider()”.
Here, we have divided Dynamic Form into two parts:
1. Parent Row
2. Child Row
Child Row is the place where we temporarily add our data and once we click on update, final data will be added in Parent Row.

// Print custom meta box content
function add_image_slider() {
    global $post;
    $imageSliderData = get_post_meta($post->ID, 'image_data', true);
     // Use nonce for verification
    wp_nonce_field(plugin_basename(__FILE__), 'noncename_so_image');

Dynamic form will contain visible part as “Parent Row” of our custom code.
This will show the post data. With ‘Edit’ and ‘Remove Row’ buttons.

...
<div id="dynamic_form">
        <div id="parent-row" >
            <?php
            if (isset($imageSliderData['image_url'])) {
                for ($i = 0; $i < count($imageSliderData['image_url']); $i++) {
            ?>
                <!--original field-->
                    <div class="field_row">
                        <div class="field_left">
                            <div class="form_field">
                                <input type="hidden" class="meta_image_url" 
                                    name="image[image_url][]" 
                                    value="<?php esc_html_e($imageSliderData['image_url'][$i]); ?>" />
                            </div>
                        </div>
 
                        <div class="field_right image_wrap">
                            <img src="<?php esc_html_e($imageSliderData['image_url'][$i]); ?>"
                                      height="130" width="128" />
                        </div>
                        <div class="field_right">
                            <input type="button" class="button btn-add" value="Edit" 
                                       onclick="add_image(this)" title="Click to edit image"/><br />
                            <input type="button" class="button btn-remove"  
                                      value="Remove Row"    
                                      onclick="remove_field(this)" title="Click to remove image"/>
                        </div>
                        <div class="clear" /></div> 
                    </div>
                <?php
            } // endif
        } // endforeach
        ?>
        </div>
</pre>

Child Row is added when we click on “Add Row” button. And a row will be added with two buttons “Add” and “Remove Row”. And in Backstage HTML under child-row div will be appended to parent-row.

...    
<!--empty jquery field-->
        <div style="display:none" id="child-row">
            <div class="field_row">
                <div class="field_left">
                    <div class="form_field">
                        <!--<span> No image selected</span>-->
                        <input type="hidden" class="meta_image_url" 
                                  name="image[image_url][]" value=""/>
                    </div>
                </div>
                <div class="field_right image_wrap">
                </div> 
                <div class="field_right"> 
                    <input type="button" class="button btn-add" 
                               value="Add" onclick="add_image(this)" /><br />
                    <input type="button" class="button btn-remove" 
                               value="Remove Row" onclick="remove_field(this)" /> 
                </div>
                <div class="clear"></div>
            </div>
        </div>
 
        <div id="add_field_row">
            <input class="button btn-addRow" type="button"
                     value="Add Row" onclick="add_field_row();" 
                     title="Click to add another row"/>
        </div>
    </div>
    <?php
}
...

When we save the added field for repeater, it will become a part of Parent Row after Checking the save status using wordpress functions. We’ve used wordpress default “update_post_meta” for saving.

...    
...
add_action('save_post', 'save_update_image_slider', 10, 2);
 
// Save post action, for Image slider
function save_update_image_slider($post_id, $post_object) {
// Checks save status
    $is_autosave = wp_is_post_autosave($post_id);
    $is_revision = wp_is_post_revision($post_id);
    $is_valid_nonce = ( isset($_POST['prfx_nonce']) &&         wp_verify_nonce($_POST['prfx_nonce'], basename(__FILE__)) ) ? 'true' : 'false';
 
// Exits script depending on save status
    if ($is_autosave || $is_revision || !$is_valid_nonce) {
        return;
    }
 
    if ($_POST['image']) {
        $imageSliderData = array(); // Build array for saving post meta
        for ($i = 0; $i < count($_POST['image']['image_url']); $i++) {
            if ('' != $_POST['image']['image_url'][$i]) {
                $imageSliderData['image_url'][] = $_POST['image']['image_url'][$i];
            }
        }
 
        if ($imageSliderData)
            update_post_meta($post_id, 'image_data', $imageSliderData);
        else
            delete_post_meta($post_id, 'image_data');
    }
    else {
        delete_post_meta($post_id, 'image_data');
    }
}

PHP Code
This will include custom CSS and JS.

add_action('admin_enqueue_scripts', 'include_custom_js_css');
// Add custom JS and CSS
function include_custom_js_css() {
   wp_enqueue_script('custom-js', get_theme_file_uri('/js/custom-js.js'), array(), '1.0', true); //JS 
   wp_enqueue_style('custom-css', get_theme_file_uri('css/custom-css.css'), array(), '1.0'); //CSS
}

Javascript code

Add below mentioned code to a separate JS file and include it in functions.php. add_image() function will show Default Media Uploader Pop-up of WordPress. This function will be called on click of Add button.

custom-js.js

//--------Start Image Slider Box JS-----------
function add_image(obj) {
    var parent = jQuery(obj).parent().parent('div.field_row');
    var inputField = jQuery(parent).find("input.meta_image_url");
    tb_show('Select Your Image', 'media-upload.php?type=image&amp;TB_iframe=true', false);
    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 + '" width="128" height="130" />');
        tb_remove();
    };
    return false;
}
 
function remove_field(obj) {
    var parent = jQuery(obj).parent().parent();
    parent.remove();
}
 
function add_field_row() {
    var row = jQuery('#child-row').html();
    jQuery(row).appendTo('#parent-row');
}
 
//----------End Image Slider Box JS------------

Style

Used in creating Styles for Layout and Buttons in Admin
custom-css.css

.field_left {float:left;}
.field_right {float:left;margin-left:10px;}
.clear {clear:both;}
 
#dynamic_form {width:100%;}
#dynamic_form input[type=text] {width:300px;}
#dynamic_form .field_row {
    width: 100%;
    border-bottom: 1px solid #ddd;
    margin-bottom:15px;
    padding:10px;
}
#dynamic_form label {padding:0 6px;} 
.btn-add{width: 95px !important;}
.btn-remove{width:95px !important;margin-top: 4px !important;}
.btn-addRow{
    color: #fff !important;
    font-size: 13px !important;
    text-align: center !important;
    text-decoration: none !important;
    background: #2EA2CC !important;
    border: #0074A2 solid 1px !important;
}

And there you have it! Hopefully, you now have a broader understanding of adding custom code for image Repeater to your WordPress site and what method best suits your current situation.

Top