Print Custom Field Names And Values

This code enables you to efficiently output a specific list of custom field names and values conditionally. The custom field name and value are only printed if the value for each name exists.

The code uses the foreach loop function to display your custom field names with values rather than individual calls to each custom field so its more efficient.

Here’s the front end output without any CSS:

custom-field-loop

This example enables you to print a list of specific custom fields without printing all custom fields for each post. In this example the data is hooked after the content of each single post, if it exists. If empty, there is no output.

Here’s the code for logged in members:


Comments

2 responses to “Print Custom Field Names And Values”

  1. Tatiana M Avatar
    Tatiana M

    Hi Brad,
    If I wanted to add custom fields before the content on a custom post type (dogs), how would I go about modifying this code to do that? Basically, I’d like to use this template
    http://hoofnpawsamoyeds.com/dog/pop/ but modify it to work with genesis child themes instead. There are repeating custom fields in three different sections: below the featured image (Awards), the main information about the dog, in this case (Pop), and the table below it, (Notable Offspring). I’ve tried looking through the code for this theme, but the parts that I want are scattered throughout in different files and I don’t know where to begin to convert it to work with genesis.

    If you need to look at the code, I can upload the entire theme and send it to you to work with.

    I do also own ACF Pro, if it is easier to work with a plugin in this instance.

    Any help is appreciated (I couldn’t find a way to email you directly with this request, so I’m posting it in the comments. Hope that’s okay!

    1. Use is_singular(‘dog’) with any genesis hook https://wpsites.net/genesis-hooks/.

      [code]
      add_action( ‘genesis_before_content’, ‘function_name’ );
      function function_name() {

      if ( is_singular(‘dog’) )

      $value = get_post_meta( get_the_ID(), ‘key’, true );

      if ( ! empty( $value ) ) {

      echo ‘

      ‘. $value .’

      ‘;

      }
      }
      [/code]

      Or, add the code to a single-dog.php file without the conditional tag.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.