Site icon WP Smith

How to Add a Custom Field Shortcode to Use Any Custom Field in Posts

In another tutorial I am writing, one for non-coders, I needed a way to pull in custom fields into the post. Currently (and sadly), in Genesis there is no way to do this; however, Genesis does have a great php function that already does this, genesis_get_custom_field(). So turning that into a shortcode is rather easy. Just add the following to your functions.php code:

[php]
add_shortcode( 'post_field', 'genesis_post_field_shortcode' );
/**
* Returns the value of a custom field.
*
* Supported shortcode attributes are:
* field (field name),
*
* @param array $atts Shortcode attributes
* @return string Shortcode output
*/
function genesis_post_field_shortcode( $atts ) {

$defaults = array(
'field' => '',
);
$atts = shortcode_atts( $defaults, $atts );

return genesis_get_custom_field( $atts['field'] );
}
[/php]
To use the shortcode, you just insert [ post_field field="my_field_name"] (without the space in the front) and boom! It works!