Skip to content

Editing custom fields

scribu edited this page Mar 7, 2011 · 23 revisions

Since custom fields can be used in so many ways, you have to make some code replacements in your theme:

Replace something like this:

<?php echo get_post_meta( $post->ID, 'my_key', true ); ?>

with this:

<?php editable_post_meta( get_the_ID(), 'my_key', 'textarea' ); ?>

If you want to prevent errors when the plugin is deactivated, you can combine both:

<?php
if ( function_exists( 'editable_post_meta' ) )
  editable_post_meta( get_the_ID(), 'my_key', 'textarea' );
else
 echo get_post_meta( $post->ID, 'my_key', true );
?>

The third parameter is optional and allows you to pick which type of field you want: input, checkbox, select, textarea or rich.

Making a <select> element

<?php 
editable_post_meta( get_the_ID(), 'my_key', array(
	'type' => 'select',
	'values' => array(
	    'val_1' => 'Title 1', 
	    'val_2' => 'Title 2'
	)
) );
?>

When you double-click on the above custom field, a dropdown will show up with the values you specified.

Handling multiple values

If you have a custom field with multiple values, you can use get_editable_post_meta(). For example:

<ul>
<?php
$values = get_editable_post_meta( get_the_ID(), 'my_key' );
foreach ( $values as $value )
	echo '<li>' . $value . '</li>';
?>
</ul>

The editable_custom_field() template tag is located in fields/post.php.

Clone this wiki locally