Skip to content

Editing custom fields

scribu edited this page May 1, 2012 · 23 revisions

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

First, here's how the original code looks like:

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

You'll need to replace that with something like this:

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

Or like this:

<?php editable_post_meta( $post->ID, 'my_key', 'input' ); ?>

That third parameter represents what kind of editing interface you want. Here are other possible values:

A WYSIWYG interface

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

An <input> element

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

A <textarea> element

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

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'
	)
) );
?>

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.

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 );

The above code would go inside your theme's functions.php file or in another plugin.