Skip to content

Instantly share code, notes, and snippets.

@rahilwazir
Last active September 14, 2017 10:32
Show Gist options
  • Save rahilwazir/60943f0cd0d7efd016dde6547e21090f to your computer and use it in GitHub Desktop.
Save rahilwazir/60943f0cd0d7efd016dde6547e21090f to your computer and use it in GitHub Desktop.
Repeater Field in WordPress

Repeater Field in WordPress

PHP

Inject the following script to your PHP file

function my_enqueue_scripts() {
    wp_enqueue_script( 'phq', '/your/path/to/script.js', [ 'jquery', 'underscore', 'wp-util' ], '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );

The dependencies are required for this example, if you don't want to use jQuery and Underscore template engine it's upto you. But do change the HTML/JS below respectively, I will not show here how-to.

Your HTML content block, which includes two buttons to Add and Remove the repeater fields as follows

HTML

<div class="container">
    <button type="button" class="my-field-add">Add</button>
    
    <div class="fields"></div>
</div>

<!-- Template -->
<script type="text/html" id="tmpl-my-field-group">
    <span class="field-group">
        <input type="text">
        <button type="button" class="my-field-remove">Remove</button>
    </span>
</script>
<!-- End Template -->

Your script.js file would look like this

JavaScript

( function( $ ) {
    var template = wp.template( 'my-field-group' );
    
    // Add
    $( '.container' ).on( 'click', '.my-field-add', function() {
        $( '.fields' ).append( template() );
    } );
    
    // Remove
    $( '.container' ).on( 'click', '.my-field-remove', function() {
        $( this ).closest( '.field-group' ).remove();
    } );
} ) ( jQuery );

and you are done. Enjoy!

@adeel-raza
Copy link

Awesome. Thanks for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment