Skip to content

Editing custom fields

scribu edited this page Oct 20, 2011 · 23 revisions

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

Basic usage

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.

Escaping

By default, custom fields are not escaped in any way. If you want, for example, to prevent HTML from being inserted, you can use the 'post_meta' filter introduced by FEE:

` function my_custom_field_escaping( $content, $post_id, $key ) { if ( 'some_key' == $key ) return strip_tags( $content );

return $content;

} add_filter( 'post_meta', 'my_custom_field_escaping', 10, 3 ); `

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