Loading Hasty Logo
Blog
How to display a custom meta field in WordPress
Quick Tips
18. November 2017
timelapseEstimated reading time:

How to display a custom meta field in WordPress

You have generated meta fields with Hasty, but don't know how to show them in a page?

If you want to display a custom meta field on your WordPress site, you have to edit your theme files. Here are two solutions how you can achieve this. The first solution will be a simple function get_post_meta(). The other method is through a shortcode, which also uses the function, but with the advantage that you can output the code with a simple shortcode in your editor without editing the theme files.

Creating the metabox and fields with Hasty

First of all you need to create the custom meta fields. The best way to achieve this is using the Hasty Metabox Generator. Type in a title for the metabox for example: “Options", choose the post types, where to show the meta box and then create the fields you want. Then copy the whole code and paste it in your functions.php.

Important: You need the ID of the field to display it. If you don’t type in any ID, it will be created automatically.

class optionsMetabox {
	private $screen = array(
		'post',
		'page',
	);
	private $meta_fields = array(
		array(
			'label' => 'country',
			'id' => 'country_19145',
			'type' => 'text',
		),
		array(
			'label' => 'email',
			'id' => 'email_51500',
			'type' => 'text',
		),
	);
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
		add_action( 'save_post', array( $this, 'save_fields' ) );
	}
	public function add_meta_boxes() {
		foreach ( $this->screen as $single_screen ) {
			add_meta_box(
				'options',
				__( 'Options', 'textdomain' ),
				array( $this, 'meta_box_callback' ),
				$single_screen,
				'advanced',
				'default'
			);
		}
	}
	public function meta_box_callback( $post ) {
		wp_nonce_field( 'options_data', 'options_nonce' );
		$this->field_generator( $post );
	}
	public function field_generator( $post ) {
		$output = '';
		foreach ( $this->meta_fields as $meta_field ) {
			$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
			$meta_value = get_post_meta( $post->ID, $meta_field['id'], true );
			if ( empty( $meta_value ) ) {
				$meta_value = $meta_field['default']; }
			switch ( $meta_field['type'] ) {
				default:
					$input = sprintf(
						'<input %s id="%s" name="%s" type="%s" value="%s">',
						$meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
						$meta_field['id'],
						$meta_field['id'],
						$meta_field['type'],
						$meta_value
					);
			}
			$output .= $this->format_rows( $label, $input );
		}
		echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
	}
	public function format_rows( $label, $input ) {
		return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
	}
	public function save_fields( $post_id ) {
		if ( ! isset( $_POST['options_nonce'] ) )
			return $post_id;
		$nonce = $_POST['options_nonce'];
		if ( !wp_verify_nonce( $nonce, 'options_data' ) )
			return $post_id;
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
			return $post_id;
		foreach ( $this->meta_fields as $meta_field ) {
			if ( isset( $_POST[ $meta_field['id'] ] ) ) {
				switch ( $meta_field['type'] ) {
					case 'email':
						$_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
						break;
					case 'text':
						$_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
						break;
				}
				update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
			} else if ( $meta_field['type'] === 'checkbox' ) {
				update_post_meta( $post_id, $meta_field['id'], '0' );
			}
		}
	}
}
if (class_exists('optionsMetabox')) {
	new optionsMetabox;
};
Copy to clipboard
Here is an example metabox with two fields: country (ID: country_19145) and email (ID: email_51500)

Solution 1: Using the get_post_meta() function in your theme file

The get_post_meta() function retrieves the post meta field for a post-type. It has three parameters:
get_post_meta( $post_id, $key, $single );

$post_id: This parameter is required and should be the ID of the post, page or post-type

$key: This parameter is optional, but for our purpose it’s essential. Here we put in the meta-key, which is our field ID (for example: country_19145).

$single: This parameter is also optional, but we have to overwrite the default (false) with true, because we want to output a single value.

Open the file from your themes folder where you want to output the meta field. In this example I will choose the single.php, which renders a single post. Put the following function in your code to display the field value from “country" on your single post page:

echo get_post_meta( get_the_ID(), 'country_19145', true ); 
Copy to clipboard
Outputs the value of the meta field "country".

Solution 2: Using a shortcode to display the meta field value

First of all we need to create the shortcode with the add_shortcode() function. The shortcode uses the same function like in first solution. The advantage is that you can easily use the shortcode in the WordPress editor without editing theme files. Furthermore you can change easily which meta field will be outputted by changing an attribute in the shortcode.

Open your functions.php and add the following function, which creates the shortcode.

// Add shortcode [metafield key="" pid=""]
function metafield_func( $atts ) {
	$atts = shortcode_atts( array(
		'key' => NULL,
		'pid' => NULL,
	), $atts, 'metafield' );
	
	if( !$atts['key']) return;
	if ($atts['pid']) {
		$pid = $atts['pid'];
	} else {
		$pid = get_the_ID();
	}
	return get_post_meta( $pid, $atts['key'], true );
}
add_shortcode( 'metafield', 'metafield_func' );
Copy to clipboard
Adds the metafield shortcode: [metafield key="" pid=""]

Now you can use the shortcode in any page. The “pid"-attribute of the shortcode is optional. It can output a meta field of a specific page or post, otherwise it will output the meta field of the current page.

So if we want to output our country meta field (which we created earlier) in a post, just paste the following shortcode in the editor:

[metafield key="country_19145"]

If you want to output the meta field of another post in this post, then just insert ID of the post in the “pid"-attribute.

[metafield key="country_19145" pid="12"]