Add custom fields via Shortcodes in a WordPress post

Adding shortcodes with custom fields is very easy, although we have to use a series of codes for it.

We are going to do it in two different ways, and we are going to see the pros and cons of doing it one way or the other.

The video tutorial:

Subscribe to my channel:  

First we will do it manually:
To do this we go to Appearance –> Editor –> and edit the functions.php file and add the following code:

add_shortcode('field', 'shortcode_field');
function shortcode_field($atts){
     extract(shortcode_atts(array(
                  'post_id' => NULL,
               ), $atts));
  if(!isset($atts[0])) return;
       $field = esc_attr($atts[0]);
       global $post;
       $post_id = (NULL === $post_id) ? $post->ID : $post_id;
       return get_post_meta($post_id, $field, true);
}

Once done, we just go to the input where we want to add the custom field shortcode and add the custom field as follows:

[field "my_key"]

In the following image you can see it in a real case:
shortcode-field-customize

And the result is the following:
result-custom-field

Now we are going to do it without editing the template (exclusive for Genesis templates):

The grace of doing it without editing the template is that if there is an update to the template we can update it without fear of losing the changes we have made.
Remember that in the method above we modified the functions.php file of our template.

If you use a Genesis template from Studiopress we can do it without editing the template thanks to Genesis Extender plugin

The plugin You have it available for free in the Premium Zone or you can buy here and it costs 39$

If you are not subscribed to the Premium Zone you can give sign up for €10/month here

Once we have the Genesis Extender plugin we go to the Genesis menu -> Extender Custom and in the "Functions" tab we paste it:
genesis-extender-custom-fields

And voila, we have it working.
Now it doesn't matter if we update the template or the Genesis Extender plugin itself, we don't lose the changes since they are saved in the database.

I hope it has been useful to you 😉
regards
Oscar

1 comment on “Add custom fields through Shortcodes in a WordPress post”

  1. Hi!

    I would like to know if it would be possible to include a shortcode in the value of a custom field. I have tried but the code of the shortcode appears: [here shortcode]

    It was in case there is a plugin or an option that allows shortcodes to work within a value in a custom field.

    Thank you!!

Leave a comment