2. get_field() и the_field() | Field Forge - Произвольные поля, созданные для скорости
Скачать Войти

2. get_field() и the_field()

Две самые основные функции в Field Forge. get_field() извлекает значение; the_field() выводит его напрямую.

get_field( $selector, $post_id )

Извлечь одно значение поля.

Параметры:
ПараметрТипПо умолчаниюОписание
$selectorstringИмя поля (например, 'subtitle') или ключ поля (например, 'field_abc123')
$post_idint\string\falsefalseID записи, 'options', 'user_123', 'term_45', 'comment_67' или false для текущей записи в цикле
Возвращает: mixed — значение поля, отформатированное в соответствии с настройкой return_format поля. Возвращает null, если не найдено. Справка по формату ID записи:
ФорматПримерЦель
falseget_field('title')Текущая запись (требуется цикл)
intget_field('title', 42)Конкретная запись по ID
'options'get_field('logo', 'options')Страница опций (стандартный слаг)
'user_N'get_field('bio', 'user_5')Метаданные пользователя для ID пользователя 5
'term_N'get_field('color', 'term_12')Метаданные термина для ID термина 12
'comment_N'get_field('rating', 'comment_99')Метаданные комментария для ID комментария 99
php
// Current post (inside The Loop)
$title = get_field( 'custom_title' );

// Specific post
$price = get_field( 'product_price', 42 );

// Options page
$logo = get_field( 'site_logo', 'options' );

// User meta
$bio = get_field( 'biography', 'user_' . get_current_user_id() );

// Term meta
$category_color = get_field( 'brand_color', 'term_' . $term_id );
Примеры формата возврата по типу поля:
php
// Image field with return_format = 'array' (default)
$image = get_field( 'hero_image', 123 );
// Returns: ['ID' => 55, 'url' => '...', 'width' => 1200, 'height' => 630, 'alt' => '...', 'title' => '...']

// Image field with return_format = 'url'
$image_url = get_field( 'hero_image', 123 );
// Returns: 'https://example.com/wp-content/uploads/2024/hero.jpg'

// Image field with return_format = 'id'
$image_id = get_field( 'hero_image', 123 );
// Returns: 55

// Select field with return_format = 'value'
$status = get_field( 'order_status', 200 );
// Returns: 'processing'

// Select field with return_format = 'label'
$status_label = get_field( 'order_status', 200 );
// Returns: 'Processing'

// Select field with return_format = 'array'
$status_full = get_field( 'order_status', 200 );
// Returns: ['value' => 'processing', 'label' => 'Processing']

// True/false field always returns bool
$is_featured = get_field( 'is_featured', 123 );
// Returns: true or false

// Relationship field with return_format = 'object'
$related = get_field( 'related_posts', 42 );
// Returns: [WP_Post, WP_Post, WP_Post]

// Repeater field returns array of row arrays
$rows = get_field( 'team_members', 42 );
// Returns: [['name' => 'Alice', 'role' => 'Dev'], ['name' => 'Bob', 'role' => 'Design']]

the_field( $selector, $post_id )

Выводит значение поля. Эквивалентно echo get_field(...).

Параметры:
ПараметрТипПо умолчаниюОписание
$selectorstringИмя поля или ключ поля
$post_idint\string\falsefalseТо же самое, что и get_field()
Возвращает: void (выводится напрямую).
php
<!-- Current post -->
<h1><?php the_field( 'page_heading' ); ?></h1>

<!-- Link with field values -->
<a href="<?php the_field( 'cta_link' ); ?>">
    <?php the_field( 'cta_text' ); ?>
</a>

<!-- Options page value -->
<footer>
    <p><?php the_field( 'footer_copyright', 'options' ); ?></p>
</footer>

<!-- User profile -->
<div class="author-bio">
    <p><?php the_field( 'biography', 'user_' . get_the_author_meta( 'ID' ) ); ?></p>
</div>

<!-- Specific post -->
<div class="promo-banner">
    <h3><?php the_field( 'promo_headline', 99 ); ?></h3>
    <p><?php the_field( 'promo_description', 99 ); ?></p>
</div>

ИИ-ассистент Forge Онлайн

Привет! Я ИИ-ассистент Field Forge. Спрашивайте меня о чём угодно по плагину — настройка, возможности, устранение неполадок или разработка.

Только что
На базе Forge AI · Просмотр документации