We are already aware of the incredible power and flexibility of WordPress, which is one of the biggest reasons for its popularity among its users. And, if we look at the reasons for its flexibility, the first thing that comes to our mind is Custom Field.
Custom fields enable you to add any additional information to your posts and pages. It’s like defining your own variables and values for posts/pages. Custom Fields are powerful tools for customizing template files; these are special fields in the WordPress database that you can create yourself by giving them a name (which can be then shared by all other posts or pages) and assigning a value for the particular post.
This arbitrary extra information is known as meta-data. Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the entered information that will appear in the meta-data list on each respective post. Shown below the screenshot of the word press option where we add custom fields while adding/editing a post/page.
NOTE: In the examples for Custom fields shown below, we explain about adding 5 custom fields for “Artists” post to store the additional information for an artist i.e. “artist image”, “2 small images of artist’s artwork” and “2 large images of artist’s artwork” along with many other custom fields.
Though Custom fields are really flexible they’re not perfectly user-friendly, especially for a layman.
Here are the main reasons:
-
2. Also, sometimes In order to make things easier for users we add inline tips, and inputs (in the form of suggestions or examples) appropriate to the field. This is not there in the above case. For a normal User, submitting a ready-made form is always much easier then selecting a key and then adding value for that key.
How to change this layout to make it more user-friendly and easy to understand?
With a very little knowledge of PHP, you can change this default display of Custom fields and present it in a much simple, user-friendly and easy to understand layout for your user.
It looks like this:
To present your custom fields in a proper manner, and group related fields, you need to add the following piece of code into your theme’s functions.php i.e. \wp-content\themes\your_theme\functions.php
Step 1
Create an array to define custom fields and information to generate the form.
$arr_artist_details =
array (
"artist-image-url" => array(
"name" => "artist-image-url", // custom field name i.e. the KEY
"type" => "input", // type of custom field i.e. required form's element type could be input/textarea/select etc ...
"title" => "Artist Image URL", // title to be used for the key i.e. form's label
"description" => "field description / help tip", // field description (if any)
"scope" => array("post","page")), // define the scope in posts/pages
"artwork1-small-image-url" => array(
"name" => "artwork1-small-image-url",
"type" => "input",
"title" => "Artwork 1 Small Image URL",
"description" => "field description / help tip",
"scope" => array("post","page")),
"artwork1-large-image-url" => array(
"name" => "artwork1-large-image-url",
"type" => "input",
"title" => "Artwork 1 Large Image URL",
"description" => "field description / help tip",
"scope" => array("post","page")),
"artwork2-small-image-url" => array(
"name" => "artwork2-small-image-url",
"type" => "input",
"title" => "Artwork 2 Small Image URL",
"description" => "field description / help tip",
"scope" => array("post","page")),
"artwork2-large-image-url" => array(
"name" => "artwork2-large-image-url",
"type" => "input",
"title" => "Artwork 2 Large Image URL",
"description" => "field description / help tip",
"scope" => array("post","page"))
);
Step 2
Function to generate the form for the above array.
function generate_artist_form() {
global $post, $arr_artist_details;
foreach($arr_artist_details as $meta_box) {
echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';
echo'<div><span style="width:200px; float:left">'.$meta_box['title'].'</span>';
if( $meta_box['type'] == "input" ) {
$meta_box_value = get_post_meta($post->ID, $meta_box['name'], true);
if($meta_box_value == "")
$meta_box_value = $meta_box['std'];
echo'<input type="text" name="'.$meta_box['name'].'" value="'.$meta_box_value.'" size="98" /><br />';
} elseif ( $meta_box['type'] == "select" ) {
echo'<select name="'.$meta_box['name'].'">';
foreach ($meta_box['options'] as $option) {
echo'<option';
if ( get_post_meta($post->ID, $meta_box['name'], true) == $option ) {
echo ' selected="selected"';
} elseif ( $option == $meta_box['std'] ) {
echo ' selected="selected"';
}
echo'>'. $option .'</option>';
}
echo'</select>';
}
echo '</div>';
echo'<p><label for="'.$meta_box['name'].'">'.$meta_box['description'].'</label></p>';
}
}
Step 3
Function to save the post data i.e. handle the save action.
function save_form_data( $post_id ) {
global $post, $arr_artist_details;
foreach($arr_artist_details as $meta_box) {
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
$data = $_POST[$meta_box['name']];
if(get_post_meta($post_id, $meta_box['name']) == "")
add_post_meta($post_id, $meta_box['name'], $data, true);
elseif($data != get_post_meta($post_id, $meta_box['name'], true))
update_post_meta($post_id, $meta_box['name'], $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'], get_post_meta($post_id, $meta_box['name'], true));
}
}
Step 4
Function to create Custom field meta box (by using WP’s add_meta_box() function and passing the "generate_artist_form" function as a parameter).
function create_meta_box() {
global $theme_name, $arr_artist_details;
if (function_exists('add_meta_box')) {
add_meta_box( 'my-custom-fields', 'Gallery - Artist Details', 'generate_artist_form', 'post', 'normal', 'low' );
}
}
Finally, Hook the functions to specific actions.
add_action('admin_menu', 'create_meta_box'); add_action('save_post', 'save_form_data');
It’s as simple as that, even with limited knowledge in PHP, you can simply paste this code in your functions.php file and carefully do the changes.
Additional tips:
- You can rename the array name and the custom functions like
generate_artist_form(), save_form_data() and create_meta_box() as per your requirement. If you are doing this, make sure to replace all its occurrences.
- If you want to add different form fields other than
"input", you need to specify the related "type" in the array and add a condition based on the type to generate that field in "generate_artist_form" function (in this case)
- No changes are required in the save_form_data function.
- Custom fields box/block heading can be changed from
create_meta_box() function. Here the second argument used in the add_meta_box() function is the one which needs to be changed in this case. For complete details, kindly refer WP reference.
Image Credits