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:
It shows all the added custom fields in a drop-down where the user has to select the required Custom Field – KEY manually to enter the VALUE. This increases the possibility of error due to invalid/inappropriate key selection and it is hard to identify the custom field – KEY where many Custom fields are defined. This is how it looks:
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
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")) );
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="'.ks29so_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>'; } }
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 ( !ks29so_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)); } }
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:
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."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)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.
Works fine, thanks for the tip!
One thing though i’ve seen while quickly testing it, you loose the “update” button function in the custom fields box. I can only be updated by cvhanging the value in the “Gallery – artist detail” box.
Great post anyway.
How complicated. You have to input PHP to get this to work? ExpressioneEngine is much simpler when it comes to “custom fields”.
Great tutorial, its really enjoyable to work on wordpress due to its simplicity. Although it looks a bit complicated to code this, but it enhances the user experience to a great level.
Great tutorial.
Thanks for scripts.
Tha’s indeed a great article! Thanks Ashish for simplifying wordpress to this extent.
As an entrepreneur who loves hacking WordPress, the above are some great ideas! Saving this post to my bookmarked files – thanks for writing it.
Hi,
great post… But I have a problem:
I get this error
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in functions.php on line 174
which is : “artist-image-url” => array(
Thanks
useful information for wordpress developers. thanks
Double post I know: I tried in another theme I have this error
? ?>
Warning: Invalid argument supplied for foreach() in
foreach($arr_artist_details as $meta_box)
thx
Thanks for the tips
great post
how to update all custom fields?no update button?
Wow, what a great article to share with everyone.
However, I just wondering how to make the “browse” button for uploading kind of images or files for custom field and I’m sure that’d be great if you could do that by this code.
Many thanks!
How do we append this to a specific custom post? I have a custom post section and would like to have specific custom field sets per custom post.
Thanks for any help.
This is a really helpful tutorial! I found just what I needed from this. Thank you!
This is great. The only concern is, if the user updates a field in wp’s own “Custom Fields” box by selecting that fields’ Update button, and then happens to select the main Update button in the “Publish” box, the post is updated with the content that is in the “Gallery – artist detail” box. Negating the original field update.
Really a good tutorial, Thanks for sharing.
Hey if you get Warning: Invalid argument supplied for foreach() in lines
foreach($arr_artist_details as $meta_box) {
what can be wrong?
I started with a wordpress.com blog several years ago. After learning about the advantages of a self-hosted blog, I soon converted to WordPress.org. I agree that newbies should start with wordpress.com because it is much easier to convert to the self-hosted wordpress and knowing the dashboard,etc. A self-hosted blog shows how serious you are as an online business professional. A great way to brand yourself, your products and services. Plus, it is your domain for life. This is a great post with really good information especially for those just starting out. Thanks for sharing!
I started with a wordpress.com blog several years ago. After learning about the advantages of a self-hosted blog, I soon converted to WordPress.org. I agree that newbies should start with wordpress.com because it is much easier to convert to the self-hosted wordpress and knowing the dashboard,etc.Very Good Post Thankx
several years ago. After learning about the advantages of a self-hosted blog,
Great codes. it works.
Thanks a lot
Thanks for your tutorial. Very helpful for me. Nice sharing. http://www.handbagsdreams.com
Wow, it is really cool. I like it !
Hi,
Thank You for such a nice post but I was wondering how did you get the array list as i am trying to find them in wordpress codex i am not successfull
Good code. Would also like to have a select multiple=”multiple” box.
BTW idea where the “scope” => array(“post”,”page”)) is being used?