使用 WPCode 插件创建前端调用自定义字段的代码片段

WordPress 自定义字段(Custom Fields)可以为文章或页面添加额外信息,比如价格、副标题、来源链接等。但添加完字段后,很多用户不清楚怎样把这些内容展示在前端页面上。

本教程将带你一步步使用 WPCode 插件,创建一个简单的代码片段,在前端调用并展示自定义字段的值。无需修改主题文件,操作简单,适合刚入门的用户学习。

一、准备工作:添加自定义字段

在调用之前,需要先为文章添加自定义字段

添加步骤如下:

打开 WordPress 后台,编辑任意一篇文章

点击右上角的“三点菜单” → 选择“偏好设置”

在“面板”中勾选“自定义字段”

页面下方会出现“自定义字段”模块,点击“添加新字段”

输入字段名和字段值,例如:字段名:subtitle

字段值:这是一篇关于旅行的文章

点击“更新”保存文章。

二、安装并激活 WPCode 插件

进入后台 → 插件 → 安装插件

搜索“WPCode

点击“安装”,然后“启用”

WPCode 是一个集中管理代码片段的插件,能代替直接编辑主题代码,更加安全方便。

三、创建新的 PHP 代码片段

后台导航中打开:WPCode → Code Snippets → Add New

点击“PHP Snippet”进入代码编辑页面

标题中填写:Display Custom Field on Frontend

在代码框中输入以下内容:

add_filter( ‘the_content’, ‘add_custom_field_to_content’ );
function add_custom_field_to_content( $content ) {
if ( is_singular( ‘post’ ) ) {
$subtitle = get_post_meta( get_the_ID(), ‘subtitle’, true );
if ( $subtitle ) {
$custom_output = ‘<p style=”font-style: italic; color: #555;”>副标题:’ . esc_html( $subtitle ) . ‘</p>’;
$content = $custom_output . $content;
}
}
return $content;
}

这段代码会在文章内容顶部插入一个副标题段落,字段名为 subtitle。

在 “Insertion” 部分选择:Auto Insert → Run Everywhere

点击右上角“Activate” → “Save Snippet”保存并启用

四、前台查看效果

打开你添加过 subtitle 字段的那篇文章,刷新页面。

你会在正文最前方看到内容:

副标题:这是一篇关于旅行的文章

说明代码成功读取并输出了自定义字段内容。

五、扩展应用:支持多个字段

如果你有多个字段,比如 price、author_note 等,也可以在一个代码片段中统一输出:

add_filter( ‘the_content’, ‘add_multiple_fields_to_content’ );
function add_multiple_fields_to_content( $content ) {
if ( is_singular( ‘post’ ) ) {
$subtitle = get_post_meta( get_the_ID(), ‘subtitle’, true );
$price = get_post_meta( get_the_ID(), ‘price’, true );
$note = get_post_meta( get_the_ID(), ‘author_note’, true );

$output = ”;
if ( $subtitle ) {
$output .= ‘<p><strong>副标题:</strong> ‘ . esc_html( $subtitle ) . ‘</p>’;
}
if ( $price ) {
$output .= ‘<p><strong>价格:</strong> ‘ . esc_html( $price ) . ‘</p>’;
}
if ( $note ) {
$output .= ‘<p><strong>作者备注:</strong> ‘ . esc_html( $note ) . ‘</p>’;
}

$content = $output . $content;
}
return $content;
}

结语

使用 WPCode 插件,可以更轻松地让 WordPress 网站在不改动模板的情况下显示自定义字段内容。只需添加一段简单的 PHP 代码,就能在文章页面中输出这些附加信息。

这一方法适合初学者了解 WordPress 的内容结构,也为日后进行页面个性化打下基础。如果你想把字段显示在其他位置,比如标题上方、文章结尾或侧边栏,也可以继续使用短代码或其他 Hook 实现,欢迎进一步探索。

Leave a Reply

您的电子邮箱地址不会被公开。 必填项已用 * 标注