Post Image

WordPress Custom Fields: Tips, Tricks, and Hacks

Ever wondered what are custom fields in WordPress? Want to learn more about how custom fields work? In this article, we will show you how to user WordPress custom fields with tips, tricks, and hacks. We hope that this post will be interesting for you!

What are WordPress Custom Fields?

WordPress custom fields are metadata that are used to add additional information related to the post or page such as title, author name, date / time, etc.

By default, when you write a new post, page, or any content type, WordPress saves it into two different areas.

  • The first part is the body of your content that you add using the post editor.
  • The second part is the information about that particular content.

For example, title, author, date, time, and more. This information bit of the post is called metadata.

WordPress automatically adds all the required metadata to each post or page you create. WordPress also allows users to save their own custom metadata using custom fields.

By default, custom fields option is hidden on the post edit screen. To view it, you need to click on the ‘Screen Options’ button at the top and then check the custom fields option.

Scroll down a little, and you will be able to see the custom field meta box below the post editor.

Custom fields can be used to add any information related to the post, page, product or any content type. This meta information can be displayed in your theme. However, to do that you will need to edit your WordPress theme files.

This is why this tutorial is recommended for users familiar with editing theme files. It is also helpful for aspiring WordPress developers who want to learn how to properly use custom fields in their own themes or plugins.

Let’s take a look at how to add and use custom fields in WordPress.

Adding Custom Fields in WordPress

First you need to edit the post, product or page where you want to add the custom field and go to the custom fields meta box.

Next, you need to provide a name for your custom field and then enter its value. Click on the Add Custom Field button to save it.

The field will be stored and displayed in the custom fields meta box like this:

You can edit this custom field any time you want and then click on the update button to save your changes. You can also delete it as needed.

Now you can save your changes to store your custom field.

Displaying Custom Fields in WordPress Themes

To display your custom field on your website, you will need to edit your WordPress theme files.

First you will need to find the theme file you need to edit to display your custom field. Ideally you would want to display it on a single post page. You will need to edit the single.php or content-single.php or single-product.php file.

 

You will need to enter your custom fields code inside the WordPress loop. Look for the line that looks like this:

<?php while ( have_posts() ) : the_post(); ?>

You want to make sure that you add your code before the following line:

<?php endwhile; // end of the loop. ?>

Now you need to add this code to your theme file:

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

Don’t forget to replace key with the name of your custom field. For example, we used this code in our demo theme:

<p>Today's Mood: <?php echo get_post_meta($post->ID, 'Mood', true); ?></p>

You can now save your changes and visit the post where you added the custom field to see it in action.

Now you can use this custom field in all your other WordPress posts as well. Simply create a new post, product, page or edit an existing one. Go to the custom fields meta box and select your custom field from the drop down menu and enter its value.

Click on ‘Add Custom Field’ button to save your changes and then publish or update your post.

Hide Empty Custom Fields with Conditional Statement

In the above example, we showed you how to create a custom field and display it in your theme.

Now let’s see how to check if the custom field is not empty before displaying it. To do that, we will modify our code to first check if the field has data in it.

<?php 
$custom_field = get_post_meta($post->ID, ‘Mood’, true);
if ($custom_field) { 
?>
  <p>Today's Mood: <? echo $ custom_field; ?></p>
<?php 
} else { 
  // do nothing; 
}  
?>

Don’t forget to replace “Mood” with your own custom field name.

Adding Multiple Values to a Custom Field

Custom fields can be reused in the same post again to add multiple values. You just need to select it again and add another value.

However, the code we have used in above examples will only be able to show a single value.

To display all values of a custom field, we need to modify the code and make it return the data in an array. You will need to add the following code in your theme file:

<?php
$custom_field = get_post_meta($post->ID,  ‘Mood’, false);

if( count( $custom_field) != 0 ) { ?>
  <p>Today's Mood:</p>
  <ul>
    <?php foreach($custom_field as $field) {
            echo '<li>'.$field.'</li>';
          }
    ?>
  </ul>
<?php
}
?>

Don’t forget to replace Mood with your own custom field name.

In this example, you would notice that we have changed the last parameter of get_post_meta function to false. This parameter defines whether the function should return a single value or not. Setting it to false allows it to return the data as an array, which we then displayed in a foreach loop.

Displaying Posts with a Specific Custom Key

WordPress allows you to display posts with custom keys and their values. For example, if you are trying to create a custom archive page to display all posts with specific custom keys, then you can use WP_Query class to query posts matching those fields.

You can use the following code as an starting point.

<?php
$args = array(
    'meta_key'   => 'Mood',
    'meta_value' => 'Happy'
);
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) :
  while ( $the_query->have_posts() ) : $the_query->the_post(); 
?>
    <h2><?php the_title(); ?></h2>
<?php 
    the_content();
  endwhile; 
?>
  <!-- end of the loop -->

  <!-- pagination here -->
  <?php wp_reset_postdata(); ?>
<?php else : ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Don’t forget to replace meta_key and meta_value parameters with your own values.

Display Contributors to an Article Using Custom Fields

On many popular blogs and news sites, multiple authors contribute to write an article. However, WordPress only allows a single author to be associated with a post. You can  adding contributors as a custom field.

First you need to edit the post where you want to display co-authors or contributors. Scroll down to custom fields meta box and add author names as co-author custom field.

Now add this code to your theme files where you want to show co-authors.

<?php
$coauthors = get_post_meta($post->ID, 'co-author', false);
if( count( $coauthors ) != 0 ) { ?>
  <ul class="coauthors">
    <li>Contributors</li>
    <?php 
    foreach($coauthors as $coauthors) { 
      echo '<li>'.$coauthors.'</li>' ;
    }
    ?>
  </ul>
<?php
} else {
  // do nothing;
}
?>

To display author names separated by commas, you can add the following custom CSS.

.coauthors ul {
  display:inline;
}

.coauthors li {
  display:inline;
  list-style:none;
}

.coauthors li:after {
  content:","
}

.coauthors li:last-child:after {
  content: "";
}

.coauthors li:first-child:after {
  content: ":";
}

This is how it looked on our demo site.

Display Custom Fields Outside the Loop in WordPress

So far we have shown you all the examples where custom fields are displayed inside the WordPress loop. What if you needed to show them outside the loop? For example, in the sidebar of a single post.

To display the custom fields outside the WordPress loop add the following code:

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'key', true);
wp_reset_query();
?>

Don’t forget to replace the key with your custom field name.

Display Custom Header, Footer, Sidebar using Custom Fields

Usually most WordPress themes use the same header, footer, and sidebar on all pages. There are multiple ways to show different sidebars, header, or footer for different pages on your website. One way to do this is by using custom fields. Edit the post or page where you want to show a different sidebar and then add the sidebar as custom field.

Now you need to edit your WordPress theme files like single.php where you want to display custom sidebar. You will be looking for the following code:

<?php get_sidebar(); ?>

Replace this line with the following code:

<?php
global $wp_query;
$postid = $wp_query->post->ID;
$sidebar = get_post_meta($postid, "sidebar", true);
get_sidebar($sidebar);
wp_reset_query();
?>

This code simply looks for the sidebar custom field and then displays it in your theme. For example, if you add brpage as your sidebar custom field, then the code will look for sidebar-wpbpage.php file to display.

You will need to create sidebar- brpage.php file in your theme folder. You can copy the code from your theme’s sidebar.php file as an starting point.

Manipulating RSS feed Content with Custom Fields

Want to display additional meta data or content to your RSS feed users? Using custom fields you can manipulate your WordPress RSS feed and add custom content into your feeds.

First you need to add the following code in your theme’s functions.php file or a site-specific plugin.

function berocket_postrss($content) {
  global $wp_query;
  $postid = $wp_query->post->ID;
  $coolcustom = get_post_meta($postid, 'coolcustom', true);
  if(is_feed()) {
    if($coolcustom !== '') {
      $content = $content."<br /><br /><div>".$coolcustom."</div>";
    } else {
      $content = $content;
    }
  }
  return $content;
}
add_filter('the_excerpt_rss', 'berocket_postrss');
add_filter('the_content', 'berocket _postrss');

Now just create a custom field called “coolcustom” and add any value you like. You can use it to display advertisements, images, text, or anything you want.

Manipulate RSS Feed Title with Custom Fields

Sometimes you may want to add extra text to a post title for RSS feed users. For example, if you are publishing a sponsored post or a guest post.

First you add the following code in your theme’s functions.php file or a site-specific plugin.

function 'berocket _titlerss($content) {
  global $wp_query; 
  $postid = $wp_query->post->ID;
  $gpost = get_post_meta($postid, 'guest_post', true);
  $spost = get_post_meta($postid, 'sponsored_post', true);
  
  if($gpost !== '') {
    $content = 'Guest Post: '.$content;
  } elseif ($spost !== '') {
    $content = 'Sponsored Post: '.$content;
  } else {
    $content = $content;
  }
  return $content;
}
add_filter('the_title_rss', 'berocket_titlerss');

Next, you need to edit the post where you want to display the extra text in the title field and add guest_post and sponsored_post in custom fields.

 Sponsored and guest post custom fields

If any of these two custom fields are found with a value “true”, then it will add the appropriate text before the title. This technique can be utilized in various ways to fit whatever you like.

Set Expiration Date for Posts in WordPress Using Custom Fields

Want to set an expiration date for some posts on your WordPress site? This comes handy in situations when you want to publish content only for a specific period like running surveys or limited time offers.

One way to do this is by manually removing the post.

Another way to do this is by using custom fields to automatically expire posts after a specific time.

You will need to edit your theme files and add modify the WordPress loop like this:

<?php
if (have_posts()) :
  while (have_posts()) : the_post();
    $expirationtime = get_post_meta($post->ID, "expiration", false);
    if( count( $expirationtime ) != '' ) {
      if (is_array($expirationtime)) {
        $expirestring = implode($expirationtime);
      }
      $secondsbetween = strtotime($expirestring)-time();
      if ( $secondsbetween >= 0 ) {
        echo 'This post will expire on ' .$expirestring.'';
        the_content();
      } else {
        echo "Sorry this post expired!"
      }
    } else {
      the_content();
    }
  endwhile;
endif;
?>

Note: You will need to edit this code to match your theme.

After adding this code, you can add the expiration custom field to the post you want to expire. Make sure you add the time in this format mm/dd/yyyy 00:00:00.

Adding an expiration custom field to a WordPress post

Style Individual Posts Using Custom Fields

Want to change the look of an individual post using CSS? WordPress automatically assigns each post its own class which you can use to add custom CSS.

However, using custom fields you can add your own custom classes and then use them to style posts differently.

First you need to edit a post that you would like to style differently. Go to custom fields box and the post-class custom field.

Post class custom field

Next, you need to edit your WordPress theme files and add this code at the beginning of WordPress loop.

<?php $custom_values = get_post_meta($post->ID, 'post-class'); ?>

Now you need to find a line with the post_class() function. Here is how it looked in our demo theme:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Change this line to include your custom field value, like this:

<article id="post-<?php the_ID(); ?>" <?php post_class($custom_values); ?>>

Now if you examine the post’s source code using Inspect tool, then you will see your custom field CSS class added to the post class.

Custom field post class

Now you can use this CSS class to add custom CSS and style your post differently.

That’s all, we hope this article helped you learn more about WordPress custom fields.