About

Tuesday, January 11, 2022

How to Use Native Custom Fields in WordPress (and 5 Useful Examples)

Custom Fields in WordPress are arbitrary bits of data that you can apply to Posts, Pages, and Custom Post Types in WordPress. Metadata, as it were, in the form of key/value pairs. For example:

  • Key: subtitle / Value: They are more than they are cracked up to be
  • Key: header_color_override / Value: #e52e05
  • Key: property_url / Value: https://example.com/123

WordPress has their own documentation of this feature, so I’m not trying to replicate that. I’d just like to show you essentially what custom fields in WordPress are, how they work, how to use them, and some use cases from my own personal experience.

Table of Contents

How to Add/Edit/Remove Custom Fields in WordPress

The UI for Custom Fields in WordPress looks like this:

Showing that Custom Fields in WordPress appear below the content area of the block editor in the admin user interface.

If you don’t see it, it’s possible you may need to go under the three-dots menu, Preferences, and then find the toggle for Custom Fields and turn it on.

Showing the option to enable Custom Fields in WordPresss in the Block Editor Preferences settings. It is at the first toggle beneath the Additional settings.
The UI forces you to refresh the page when turning this feature on and off.

To add a Custom Field, type in the Key (labeled “Name”) and Value, then click Add Custom Field.

Showing a Custom Field in WordPress with a name of favorite_food and a value of burrito. There a button below the name input to add the custom field.

After it’s added, you can delete or update it from buttons below the Key/Name:

Showing a Custom Field in WordPress with a name of favorite_food and a value of burrito. There are two buttons below the name to delete or update the custom field.

After you have used Custom Fields, the keys will form into a dropdown menu for easier selection.

Showing the dropdown menu that opens when clocking on the Name field of a custom field in WordPress, allowing you to select an existing custom field.

Why use Custom Fields?

Custom Fields, along with Custom Post Types, are what make WordPress a CMS out-of-the-box rather than being limited to a simple blogging platform.

Here on CSS-Tricks, believe it or not, we use over 100 Custom Fields to do different things on this site. We tend to reach for them for relatively simple things, and it’s nice as it’s a core feature of WordPress that will continue to work forever without too much worry about compatibility or awkward technical debt.

The big idea is to open up templating possibilities. Imagine you have a page for real estate listings that has:

  • Address
  • Listing price
  • Bedrooms
  • Bathrooms
  • etc.

With custom fields, you have all that information available as discreet little chunks of data that you can echo (i.e. display) into a page template wherever you need to. That’s much more flexible than having all that data in the post content itself, even with the Block Editor.

WordPress Custom Fields use case examples

Custom Fields in WordPress can be used for so many different things! But let’s look at a five practical use cases that we have implemented here on CSS-Tricks.

1. Display additional information

Say you are publishing a video and want to have the running time of the video available to display. That’s as easy as saving the running_time as a Custom Field and displaying it wherever you’d like:

A side-by-side showing a published post on the left with the running time of a video circled in red, and the WordPress admin on the right with the running time custom field circled in the block editor showing the exact same information that is published in the post.
Note other Custom Fields in use here, like the youtube field, which we have so that we can output where the

2. Hide/Show Different Content/Features

Let’s say you want to be able to collapse the Comments area sometimes on different blog posts. You could set a custom field called should_toggle_comments and set a value of true. That’s what we do here on CSS-Tricks. In our comments.php template, we output a <ol> of all the comments, but if this custom field is there, we wrap the whole thing in a <details> element, collapsing it by default:

<?php if (get_post_meta($post->ID, 'should_toggle_comments', true)) { ?>
<details class="open-all-comments">
  <summary>Toggle All Comments (there are a lot!)</summary>
  <?php } ?>

    <ol class="commentlist" id="commentlist">
      <?php wp_list_comments('type=comment&avatar_size=512&callback=csstricks_comment'); ?>
    </ol>

  <?php if (get_post_meta($post->ID, 'should_toggle_comments', true)) { ?>
  </details>
<?php } ?>

3. Special pull quotes

Say you have a special Category archive that displays a group of posts that contain the same category, then use a custom template for that category, like category-fancypants.php. Maybe you yank out a custom quote from each article as a custom field called main-pullquote:

<blockquote>
  <?php
    echo get_post_meta($post->ID, 'main-pullquote', true);
  ?>
</blockquote>

That’s what we do for our annual end-of-year series:

A side by side showing the the main pull quote custom field in WordPress circled in red, and the category archive on the right with a red arrow pointing to the corresponding pull-quote that displays on the page.

4. Customize an RSS feed

We build a couple of totally custom RSS feeds here on CSS-Tricks that are different from what WordPress offers out of the box — one for videos and one for newsletters. The video feed in particular relies on some WordPress Custom Fields to output special data that is required to make the feed work as a feed for our video podcast.

Side by side showing the rss videos template in code on the left with the custom field part circled in red, and the RSS feed open in the browser on the right with an arrow pointing to where the corresponding code renders as the video enclosure.
The location of the video and the duration are both kept in custom fields

5. Hide/Show Author

Our sponsored posts here on CSS-Tricks are sometimes written to sound largely like an announcement from a company. They were written like that on purpose and likely have been written by multiple people by the time its actually published. A post like that doesn’t really need to be “by” someone. But sometimes sponsored posts are definitely authored by a specific person, even sometimes in the first person, which would be weird without showing a byline. That’s why we use a showSponsorAuthor custom field, to show that author if we need it.

<div class="sponsored-post-byline">
  ❥ Sponsored
  <?php if (get_post_meta($post->ID, 'showSponsorAuthor', true)) { ?>
    (Written by <?php the_author(); ?>)
  <?php } ?>
</div>

Above is a part of a template. We always mark a sponsored post as sponsored in the byline (example), but only optionally do we visually show the author (example), controlled by a custom field.

The APIs for displaying Custom Fields in WordPress

Most commonly, you’re looking to display the value of a single field:

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

That true at the end there means “give me a single value,” meaning that even if there are multiple custom fields with the same name, you’ll only get one. To get multiple of the same name, use false, like:

<?php $songs = get_post_meta($post->ID, 'songs', false); ?>
<h3>This post inspired by:</h3>
<ul>
  <?php foreach($songs as $song) {
    echo '<li>'.$song.'</li>';
  } ?>
</ul>

If you want to just dump them all out (probably mostly useful for debugging), you can do that like this:

<?php the_meta(); ?>

Although, note that this skips custom fields that start with an underscore (_), so you might consider this approach instead.

Querying for Custom Fields in WordPress

Say you wanted to query for all posts that have some particular custom field. That’s possible!

<?php
$the_query = new WP_Query(array(
  'meta_key' => 'example_field_name'
  'meta_value' => 'example_field_value' // as a string! 
));

if ($the_query->have_posts()) {
  while ($the_query->have_posts()) {
    $the_query->the_post();
    echo '<div>' . get_the_title() . '</div>';
  }
}

wp_reset_postdata();

The example above will run a query for posts that have both a custom field of example_field_name and where that field has a value of example_field_value. You could do either/or.

There is a lot more you can do here. You can use comparisons, you can get the values as numbers, and even query for multiple fields at once. We detail all that in Custom Loop/Query Based on Custom Fields.

Limiting Custom Fields in the Name dropdown

The UI dropdown for existing Custom Fields in WordPress is capped at something like 30 fields. So, if you have more than 100 different keys, the dropdown menu will look arbitrarily cut off. You can increase that number with a filter in functions.php or a plugin:

function customfield_limit_increase( $limit ) {
  $limit = 150;
  return $limit;
}
add_filter( 'postmeta_form_limit', 'customfield_limit_increase' );

Any other Block Editor concerns?

The main concern is when you can’t see the custom fields UI at all. We covered how to turn it back on (because it might default to off), so always check that. The Advanced Custom Fields plugin also turns it off, so if you’re using that plugin, note there is a line below to help turn it back on (in the case you use both, as we do).

I’m not sure there is a standard way to show the value of a custom field within a block in the block editor either. If you know of a clear way, leave a comment!

Relationship to Advanced Custom Fields

The UI for native Custom Fields in WordPress is pretty… underserved. It’s not fancy, it’s got rough edges (we find that Custom Fields have a weird way of duplicating themselves on multiple post saves, for example). It doesn’t seem like Custom Fields, while native, are a particularly first-class feature of WordPress.

Advanced Custom Fields (ACF) changes that in a big way. The spirit remains the same: attach data to content. But rather than the simple string-based key-value interface that we’ve detailed, you essentially model the data with different types and it builds really nice custom UI for you to use to input that data, even integrating directly with the Block Editor.

Imagine a podcast website where each post is an individual episode. The Block Editor might be nice for written content about the episode, but probably not a good idea for all of the metadata that goes with it. The list of guests, the duration, the location of the MP3 file, the sponsor, time jump links, etc. Custom Fields are great for that, but since there are so many, you’ll be well served by Advanced Custom Fields here instead of using native Custom Fields in WordPress. Here’s a setup example of what you get as we do on the ShopTalk Show podcast:

Side by side showing the settings for custom fields in the Advanced Custom Fields plugin on the left, and those custom fields displayed on the right in the WordPress Block Editor of a new post.

ACF, probably in an attempt to encourage using it directly and not confusing people with the native Custom Fields interface, removes the native Custom Fields interface. If you’re like us and use both types of fields, you’ll need to bring the native Custom Fields UI back to the post editor with a filter that ACF provides:

add_filter('acf/settings/remove_wp_meta_box', '__return_false');

If you use native Custom Fields in WordPress at all, you’ll want that in your functions.php file or a functionality plugin.

Note for plugin developers

Use the underscore hiding technique.

Some plugins use the Custom Fields API as a place to store post-specific data. I think that’s OK, but I’d like to implore plugin developers to always use underscore-and-plugin-prefixed custom field names when doing so.

When custom fields start with an underscore, they aren’t shown in the UI. Meaning for those of us who use the Custom Fields UI directly, it’s not cluttered with fields created by other plugins. The exception, of course, is if you intend users to be able to control what the plugin does with the Custom Field values. In that case, fine, leave those few non-underscore-prefixed fields.

_bobs_plugin_internal_value_1 // Hidden in UI
_bobs_plugin_internal_value_2 // Hidden in UI
bobs_plugin_config  // Shows in UI

_adrians_plugin_internal_value_1  // Hidden in UI
_adrians_plugin_internal_value_2 // Hidden in UI

More examples using Custom Fields in WordPress

What do you use them for?

Do you use Custom Fields in WordPress? I’m particularly curious about native custom field usage.


How to Use Native Custom Fields in WordPress (and 5 Useful Examples) originally published on CSS-Tricks. You should get the newsletter and become a supporter.



source https://css-tricks.com/use-custom-fields-in-wordpress/

No comments:

Post a Comment