如何通过Custom Types Fields插件获取WordPress字段组标题并在前端展示?
Absolutely doable! Let me walk you through how to pull that field group title (from your screenshot) and display it on your WordPress frontend—assuming you're using Advanced Custom Fields (ACF) (sounds like you might have mixed up the name a bit, "Custom Types Fields" is likely ACF).
Step 1: Grab your field group's key
First, you need the unique key for your target field group. You can find this:
- On the field group edit page: Look at the URL bar—you’ll see a key starting with
group_(e.g.,group_abc123xyz) if you have ACF's settings configured to show it. Alternatively, check the field group's ID in the URL (likepost.php?post=123&action=edit) and use that to cross-reference the key. - Or export the field group as JSON: Go to ACF → Tools → Export, select your group, and you’ll find the
keyvalue in the exported file.
Step 2: Fetch and display the title using ACF functions
ACF has a built-in function acf_get_field_group() that pulls all data for a specific field group, including the title. Here are two common ways to use it:
Option 1: Add directly to your theme template
Drop this code into the relevant theme file (like single.php, page.php, or a custom template part) where you want the title to appear:
<?php // Replace 'group_your_unique_key' with your actual field group key $target_group = acf_get_field_group('group_your_unique_key'); // Only display if the field group exists if ($target_group) { echo '<h2 class="field-group-title">' . esc_html($target_group['title']) . '</h2>'; } ?>
esc_html()is critical here—it sanitizes the title to prevent security risks like XSS attacks, always a best practice for frontend output.
Option 2: Use a shortcode for posts/pages
If you want to add the title directly in a post or page editor, add this code to your theme's functions.php file (or a custom plugin):
function display_acf_group_title($atts) { // Set default shortcode attributes $args = shortcode_atts([ 'group_key' => '', ], $atts); // Exit if no group key is provided if (empty($args['group_key'])) return ''; $field_group = acf_get_field_group($args['group_key']); // Return the sanitized title if the group exists return $field_group ? esc_html($field_group['title']) : ''; } add_shortcode('acf_group_title', 'display_acf_group_title');
Now you can use the shortcode anywhere in your content like this:[acf_group_title group_key="group_your_unique_key"]
Quick Notes
- Double-check that ACF is active on your site—this method relies on ACF's core functions.
- Test any code changes on a staging site first to avoid breaking your live site.
内容的提问来源于stack exchange,提问作者user3447137

