Return to Snippet

Revision: 42257
at March 2, 2011 07:25 by crypticsoft


Initial Code
//custom columns
add_action("manage_posts_custom_column", "my_custom_columns_fields");
add_filter("manage_edit-mysite_listings_columns", "my_listing_columns");

add_action("admin_init", "admin_init");

//custom meta box below post description when editing 
function admin_init(){
  add_meta_box("my-custom-columns-meta", "Listing Details", "my_custom_columns", "mysite_listings", "normal", "low");
}

//define listing columns
function my_listing_columns($columns)
{
	$columns = array(
		"cb" => "<input type=\"checkbox\" />",
		"title" => "Listing Title",
		"description" => "Description",		
		"address" => "Address",
		"website" => "Website",
		"phone" => "Phone Number",
		"comments" => "Comments"
	);
	return $columns;
}
//show the custom columns per post->ID
function my_custom_columns_fields($column)
{
	global $post;
	$custom = get_post_custom($post->ID);

	if ("ID" == $column) echo $post->ID;
	elseif ("description" == $column) echo $post->post_content;
	elseif ("address" == $column) echo $custom['address'][0];
	elseif ("website" == $column) echo $custom['website'][0];	
	elseif ("phone" == $column) echo $custom['phone'][0];	
	elseif ("comments" == $column) echo $post->comments;	
}
//build basic form elements to reference custom column fields for input
function my_custom_columns($column)
{
	global $post;
	$custom = get_post_custom($post->ID);

	$address = $custom['address'][0];
	$website = $custom['website'][0];	
	$phone = $custom['phone'][0];	
?>
  <p><label>Address:</label><br />
  <textarea cols="50" rows="5" name="address"><?php echo $address; ?></textarea></p>
  <p><label>Website:</label><br />
  <input type="text" name="website" size="100" value="<?php echo $website; ?>" /></p>
  <p><label>Phone:</label><br />
  <input type="text" name="phone" size="100" value="<?php echo $phone; ?>" /></p>
<?php
}

// hook into save post with our meta columns
add_action('save_post', 'save_details');

// grab all the form inputs and save them associated by post->ID
function save_details(){
  global $post;
 
  update_post_meta($post->ID, "address", $_POST["address"]);
  update_post_meta($post->ID, "website", $_POST["website"]);
  update_post_meta($post->ID, "phone", $_POST["phone"]);

}

Initial URL
http://codex.wordpress.org/Custom_Fields

Initial Description
The code references a custom post type (mysite_listings) and adds custom columns for editing the listings in the admin. This adds custom fields onto the edit / list views.

Note: You will want to change instances of "mysite_listings" with your own post type as well update the column I've defined to match your own.

Initial Title
Wordpress : Custom columns for edit / post views in the admin

Initial Tags
post, wordpress

Initial Language
PHP