Ordering items in HTML forms

Recently, I was working on a plugin to convert ACF fields to the post content for a custom post type we use. The custom post type is used by another plugin I wrote that has per-site fields for the custom post type, varying from 3 fields to 37 fields. Since I wanted to make this conversion plugin useful for all sites I decided to allow the user to choose the order in which the custom fields were inserted to the post content.

I knew that I could use an HTML form and Pippin’s method for beach processing to prevent hitting any memory limits, but I wasn’t quite sure how to order the fields.

So I did some testing and figured out that the data in the $_POST variable for an input with the same name is dependent on the order they are displayed in the form. So I started with this code to loop through the fields (and skip any non-data fields).

foreach ( $field_groups as $field_group ) {
	if ( in_array( $field_group['type'], array( 'tab' ) ) ) {
		continue;
	}

	echo "<input type='checkbox' value='{$field_group['name']}' name='fields[]' checked>{$field_group['label']}";
}

Now the next task was to allow for reordering. That was easy, I’ve used jQuery UI’s sortable before so I simply added jQuery UI to the list of dependencies for my JavaScript.

wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/plugin-admin.js', array( 'jquery', 'jquery-ui-sortable' ), $this->version, true );

…and wrapped the input’s with <li>’s and a <ul>:

<form method="post">
	<ul id="sortable">
		
	foreach ( $field_groups as $field_group ) {
		if ( in_array( $field_group['type'], array( 'tab' ) ) ) {
			continue;
		}
		echo "<li><input type='checkbox' value='{$field_group['name']}' name='fields[]' checked>{$field_group['label']}</li>";
	}
	submit_button( 'Add fields to Content', 'primary', 'submit', false );
	?>
	</ul>
</form>

…and VOILA! A drag-n-drop ordered list that allows the user to convert ACF fields to post content.

(sorry it’s been so long since I posted)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.