如何在 WordPress 中使用原生自定义字段(以及 5 个实用示例)

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。 立即开始使用 200 美元的免费额度!

WordPress 中的自定义字段是您可以应用于 WordPress 中的帖子、页面和自定义帖子类型的任意数据位。 可以说是元数据,以键/值对的形式存在。 例如

  • 键:subtitle / 值:它们比人们想象的要强大
  • 键:header_color_override / 值:#e52e05
  • 键:property_url / 值:https://example.com/123

WordPress 有自己的文档 介绍此功能,因此我不会尝试复制它。 我只是想向您展示 WordPress 中的自定义字段本质上是什么、它们如何工作、如何使用它们,以及我个人经验中的一些用例。

目录

如何在 WordPress 中添加/编辑/删除自定义字段

WordPress 中自定义字段的 UI 如下所示

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

如果您没有看到它,则可能需要转到三点菜单下的“首选项”,然后找到自定义字段的切换按钮并将其打开。

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.
在启用或禁用此功能时,UI 会强制您刷新页面。

要添加自定义字段,请键入键(标记为“名称”)和值,然后单击**添加自定义字段**。

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.

添加后,您可以从键/名称下方的按钮中删除或更新它。

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.

使用自定义字段后,键将形成一个下拉菜单以方便选择。

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.

为什么要使用自定义字段?

自定义字段以及自定义帖子类型,**是使 WordPress 成为一个开箱即用的CMS**,而不是局限于简单的博客平台。

在 CSS-Tricks 上,信不信由你,我们使用超过 100 个自定义字段来完成此站点上的不同操作。 我们倾向于将它们用于相对简单的事情,这很好,因为它是一个 WordPress 的核心功能,将永远继续工作,而无需过多担心兼容性或尴尬的技术债务。

其主要思想是扩展模板的可能性。 假设您有一个用于房地产列表的页面,其中包含

  • 地址
  • 挂牌价格
  • 卧室
  • 浴室
  • 等等。

使用自定义字段,您可以将所有这些信息作为离散的小数据块使用,并在需要时将其回显(即显示)到页面模板中。 **这比将所有这些数据都放在帖子内容本身中要灵活得多**,即使使用块编辑器也是如此。

WordPress 自定义字段用例示例

WordPress 中的自定义字段可以用于许多不同的用途! 但让我们看看我们在 CSS-Tricks 上实施的五个实用用例。

1. 显示其他信息

假设您正在发布视频,并且希望视频的播放时间可用以显示。 这就像将running_time 作为自定义字段保存并在任何您想要的地方显示它一样简单

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.
请注意此处使用的其他自定义字段,例如youtube 字段,我们将其用于输出

2. 隐藏/显示不同的内容/功能

假设您希望能够有时在不同的博文中折叠“评论”区域。 您可以设置一个名为should_toggle_comments 的自定义字段并设置值为true。 这正是我们在 CSS-Tricks 上所做的。 在我们的comments.php 模板中,我们输出所有评论的<ol>,但如果存在此自定义字段,我们会将整个内容包装在<details> 元素中,默认情况下将其折叠

<?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. 特殊的摘录

假设您有一个特殊的类别归档,它显示包含相同类别的帖子组,然后为此类别使用自定义模板,例如category-fancypants.php。 也许您可以从每篇文章中提取一个自定义引用作为名为main-pullquote 的自定义字段

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

这就是我们为年度年终系列所做的

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. 自定义 RSS Feed

我们在 CSS-Tricks 上构建了几个完全自定义的 RSS Feed,这些 Feed 与WordPress 开箱即用提供的 Feed 不同——一个用于视频,另一个用于时事通讯。视频 Feed 特别依赖于一些 WordPress 自定义字段来输出使 Feed 作为我们视频播客的 Feed 工作所需的特有数据。

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.
视频的位置和持续时间都保存在自定义字段中

5. 隐藏/显示作者

我们在 CSS-Tricks 上的赞助帖子有时会被写成公司公告的形式。 它们是故意这样写的,并且在实际发布之前可能已经由多人撰写。 这样的帖子实际上并不需要“由”某人撰写。 但有时赞助帖子肯定是由特定的人撰写的,甚至有时以第一人称撰写,如果没有显示署名,这将很奇怪。 这就是为什么我们使用showSponsorAuthor 自定义字段来显示该作者(如果需要)。

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

上面是模板的一部分。 我们始终在署名中将赞助帖子标记为赞助帖子(示例),但我们仅选择性地视觉显示作者(示例),由自定义字段控制。

在 WordPress 中显示自定义字段的 API

最常见的情况是,你希望显示单个字段的值。

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

最后的 true 表示“给我一个单个值”,这意味着即使有多个同名的自定义字段,你也只会得到一个。要获取多个同名字段,请使用 false,例如:

<?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>

如果你只想将所有自定义字段都输出(可能主要用于调试),你可以这样做:

<?php the_meta(); ?>

但是,请注意,这会跳过以下划线 (_) 开头的自定义字段,因此你可能需要考虑这种方法

在 WordPress 中查询自定义字段

假设你想要查询所有包含某个特定自定义字段的帖子。这是可以做到的!

<?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();

上面的示例将运行一个查询,查找同时具有名为 example_field_name 的自定义字段且该字段值为 example_field_value 的帖子。你也可以只使用其中一个条件。

这里你可以做更多的事情。你可以使用比较运算符,可以将值作为数字获取,甚至可以同时查询多个字段。我们在基于自定义字段的自定义循环/查询中详细介绍了所有这些内容。

限制名称下拉列表中的自定义字段

WordPress 中现有自定义字段的 UI 下拉列表最多显示大约 30 个字段。因此,如果你有超过 100 个不同的键,下拉菜单将看起来被任意截断。你可以使用过滤器functions.php 或插件中增加这个数字。

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

其他块编辑器问题?

主要问题是当你看不到自定义字段的 UI 时。我们已经介绍了如何重新启用它(因为它可能默认处于禁用状态),所以请务必检查这一点。Advanced Custom Fields 插件也会禁用它,因此如果你正在使用该插件,请注意下面有一行代码可以帮助你重新启用它(如果你同时使用两者,就像我们一样)。

我不确定是否有标准方法在块编辑器中的块内显示自定义字段的值。如果你知道一种明确的方法,请发表评论

与 Advanced Custom Fields 的关系

WordPress 中原生自定义字段的 UI 非常… 不完善。它不花哨,而且有粗糙的边缘(例如,我们发现自定义字段有一种奇怪的方式会在多次保存帖子后重复自身)。虽然是原生的,但自定义字段似乎并不是 WordPress 的一个特别高级的功能。

Advanced Custom Fields (ACF) 在很大程度上改变了这一点。其精神保持不变:将数据附加到内容。但是,与我们详细介绍的简单的基于字符串的键值界面不同,你实质上是用不同的类型对数据进行建模,它会为你构建非常好的自定义 UI 用于输入这些数据,甚至直接与块编辑器集成。

想象一个播客网站,其中每篇文章都是一个单独的剧集。块编辑器可能适合撰写有关剧集的文字内容,但可能不适合所有相关的元数据。嘉宾列表、时长、MP3 文件位置、赞助商、时间跳转链接等。自定义字段非常适合这种情况,但由于字段数量众多,你最好使用 Advanced Custom Fields 而不是 WordPress 中的原生自定义字段。以下是在 ShopTalk Show 播客 上我们所使用的设置示例。

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 为了鼓励直接使用它,避免人们与原生自定义字段界面混淆,它删除了原生自定义字段界面。如果你像我们一样同时使用这两种类型的字段,则需要使用 ACF 提供的过滤器将原生自定义字段 UI 重新带回帖子编辑器。

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

如果你在 WordPress 中使用原生自定义字段,则需要将其添加到你的 functions.php 文件或功能插件中。

插件开发人员须知

使用下划线隐藏技术。

一些插件使用自定义字段 API 来存储特定于帖子的数据。我认为这没问题,但我恳请插件开发人员在这样做时始终使用下划线和插件前缀的自定义字段名称。

当自定义字段以下划线开头时,它们不会显示在 UI 中。这意味着对于我们这些直接使用自定义字段 UI 的人来说,它不会被其他插件创建的字段弄乱。当然,例外情况是,如果你打算让用户能够控制插件如何使用自定义字段值。在这种情况下,没问题,保留这些少数几个没有下划线前缀的字段。

_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

WordPress 中使用自定义字段的更多示例

你将它们用于什么?

你是否在 WordPress 中使用自定义字段?我特别好奇原生自定义字段的使用。