Nik Custom Fields — документация

Всё, что описано в плагине, — в открытом доступе, а не за входом в админку.

Документация и примеры кода

Скопируйте любой пример, чтобы вывести поля на сайте

Примеры кода PHP

Получить значение одного поля

$value = get_custom_field( get_the_ID(), 'field_key' );
if ( $value ) {
    echo esc_html( $value );
}

Получить все поля группы

$fields = get_custom_fields( get_the_ID(), $group_id );
foreach ( $fields as $key => $value ) {
    echo '<p><strong>' . esc_html( $key ) . ':</strong> ' . esc_html( $value ) . '</p>';
}

Вывод с форматированием

echo get_custom_field_formatted( get_the_ID(), 'field_key' );

Вывод изображений галереи

$gallery = get_custom_field( get_the_ID(), 'gallery_field' );
if ( $gallery ) {
    $image_ids = json_decode( $gallery );
    echo '<div class="gallery">';
    foreach ( $image_ids as $image_id ) {
        echo wp_get_attachment_image( $image_id, 'thumbnail' );
    }
    echo '</div>';
}

Вывод связанных записей

$related_ids = get_custom_field( get_the_ID(), 'related_products' );
if ( $related_ids ) {
    $post_ids = json_decode( $related_ids );
    echo '<div class="related-products">';
    foreach ( $post_ids as $post_id ) {
        echo '<a href="' . get_permalink( $post_id ) . '">' .
             get_the_title( $post_id ) . '</a>';
    }
    echo '</div>';
}

Повторитель

Цикл по строкам повторителя

<?php
// Each row is an array keyed by the subfield keys you defined
// in the field group (Repeater structure).
$rows = get_repeater_field( get_the_ID(), 'testimonials' );

foreach ( $rows as $row ) {
    echo '<blockquote>';
    echo '<p>' . esc_html( $row['citata'] ) . '</p>';
    echo '<cite>' . esc_html( $row['avtor'] ) . '</cite>';
    echo '</blockquote>';
}
?>

Ключ каждого подполя показан в колонке «Ключ» структуры повторителя.

Проверка на пустой повторитель

<?php if ( have_repeater_rows( get_the_ID(), 'testimonials' ) ) : ?>
    <section class="testimonials">
        <?php foreach ( get_repeater_field( get_the_ID(), 'testimonials' ) as $i => $row ) : ?>
            <article class="item item-<?php echo (int) $i; ?>">
                <h3><?php echo esc_html( $row['avtor'] ); ?></h3>
                <div><?php echo wp_kses_post( $row['citata'] ); ?></div>
            </article>
        <?php endforeach; ?>
    </section>
<?php endif; ?>

Типы подполей внутри строки

<?php
foreach ( get_repeater_field( get_the_ID(), 'blocks' ) as $row ) {

    // Text / Textarea / Number — plain values
    echo esc_html( $row['title'] );
    echo (int) $row['rating'];

    // Checkbox — 1 or 0
    if ( ! empty( $row['is_featured'] ) ) {
        echo '<span class="badge">Featured</span>';
    }

    // Gallery — JSON array of attachment IDs
    $ids = json_decode( $row['images'], true );
    foreach ( (array) $ids as $id ) {
        echo wp_get_attachment_image( $id, 'medium' );
    }

    // Relationship — array of post IDs
    foreach ( (array) $row['related'] as $pid ) {
        echo '<a href="' . esc_url( get_permalink( $pid ) ) . '">'
           . esc_html( get_the_title( $pid ) ) . '</a>';
    }
}
?>

Вложенные повторители

<?php
// A repeater subfield of type "Repeater" comes back as a plain array,
// so you just loop again. Nesting works to any depth.
foreach ( get_repeater_field( get_the_ID(), 'sections' ) as $section ) {

    echo '<section>';
    echo '<h2>' . esc_html( $section['title'] ) . '</h2>';

    foreach ( $section['blocks'] as $block ) {
        echo '<div class="block">';
        echo '<h3>' . esc_html( $block['name'] ) . '</h3>';

        foreach ( $block['items'] as $item ) {
            echo '<li>' . wp_kses_post( $item['text'] ) . '</li>';
        }

        echo '</div>';
    }

    echo '</section>';
}
?>

Изображения и галереи

Возвращаемое значение зависит от настройки поля

<?php
// Set "Return value" on the field: Array / URL only / ID only.
$img = get_image_field( get_the_ID(), 'hero' );

// Return value = URL only
echo '<img src="' . esc_url( $img ) . '" alt="">';

// Return value = Attachment ID only
echo wp_get_attachment_image( $img, 'large' );

// Return value = Array
echo '<img src="' . esc_url( $img['url'] ) . '"'
   . ' alt="' . esc_attr( $img['alt'] ) . '"'
   . ' width="' . (int) $img['width'] . '"'
   . ' height="' . (int) $img['height'] . '">';

// A specific registered size from the array form
echo '<img src="' . esc_url( $img['sizes']['medium'] ) . '" alt="">';
?>

Галерея — список в том же формате

<?php
foreach ( get_image_field( get_the_ID(), 'shots' ) as $shot ) {
    // $shot is an array, a URL or an ID — whichever the field returns.
    echo '<img src="' . esc_url( $shot['url'] ) . '" alt="' . esc_attr( $shot['alt'] ) . '">';
}

// Inside a repeater row it is already formatted for you:
foreach ( get_repeater_field( get_the_ID(), 'slides' ) as $slide ) {
    echo '<img src="' . esc_url( $slide['picture']['url'] ) . '" alt="">';
}
?>

Шорткоды

Шорткод вывода поля

[nik_cf_field field="field_key"]

Выводит значение поля текущей записи.

Шорткод вывода группы

[nik_cf_group group_id="1"]

Выводит все поля группы таблицей.

Шорткод вывода галереи

[nik_cf_gallery field="gallery_field" size="medium"]

Выводит изображения из поля-галереи. Размер: thumbnail, medium, large, full

Пример для товара WooCommerce

Добавьте в single-product.php

<?php
$manufacturer = get_custom_field( get_the_ID(), 'manufacturer' );
$warranty = get_custom_field( get_the_ID(), 'warranty_months' );
$in_stock = get_custom_field( get_the_ID(), 'in_stock' );

if ( $manufacturer ) {
    echo '<p><strong>Manufacturer:</strong> ' . esc_html( $manufacturer ) . '</p>';
}

if ( $warranty ) {
    echo '<p><strong>Warranty:</strong> ' . intval( $warranty ) . ' months</p>';
}

if ( $in_stock ) {
    echo '<span class="badge in-stock">In Stock</span>';
}
?>

Пример глобальных настроек

Вывод данных компании

<?php
$company_phone = get_option_field( 'company_info', 'phone' );
$company_email = get_option_field( 'company_info', 'email' );

if ( $company_phone ) {
    echo '<p>Phone: ' . esc_html( $company_phone ) . '</p>';
}

if ( $company_email ) {
    echo '<p>Email: <a href="mailto:' . esc_attr( $company_email ) . '">' .
         esc_html( $company_email ) . '</a></p>';
}
?>

Знакомые функции полей

Эти имена функций — де-факто стандарт для плагинов полей под WordPress, поэтому существующая тема продолжает работать. На новой установке они выключены: включите «Определять общие имена функций полей, когда они свободны» во вкладке «Параметры», и каждая функция будет определена, если её не занял другой плагин. Версии с префиксом nik_ доступны всегда и являются поддерживаемым API.

// Selector first, target second.
$value = get_field( 'subtitle' );              // current post
$value = get_field( 'subtitle', 42 );          // a given post
$value = get_field( 'phone', 'option' );       // an options page
$value = get_field( 'bio', 'user_7' );         // a user
$value = get_field( 'colour', 'term_12' );     // a taxonomy term

// Loops, including nested ones.
while ( have_rows( 'sections' ) ) : the_row();
    echo esc_html( get_sub_field( 'title' ) );

    while ( have_rows( 'items' ) ) : the_row();
        echo esc_html( get_sub_field( 'name' ) );
    endwhile;
endwhile;

// Flexible content.
while ( have_rows( 'blocks' ) ) : the_row();
    if ( 'hero' === get_row_layout() ) {
        echo esc_html( get_sub_field( 'headline' ) );
    }
endwhile;

// Writing. An unknown key is refused rather than stored.
update_field( 'subtitle', 'New value', 42 );
delete_field( 'subtitle', 42 );

// The definition together with the value.
$field = get_field_object( 'subtitle', 42 );

Выборка по значению поля

Строки повторителя дублируются в плоские мета-ключи, поэтому WP_Query может обращаться внутрь них. Значения хранятся под постоянным идентификатором поля, а не под его именем, поэтому переименование ничего не стоит — получить ключ по знакомому имени поможет nik_meta_key().

// A plain field. nik_meta_key() turns the name you know into the key the
// value is actually stored under.
$q = new WP_Query( array(
    'post_type'  => 'product',
    'meta_query' => array(
        array( 'key' => nik_meta_key( 'warranty' ), 'value' => 24, 'compare' => '>=', 'type' => 'NUMERIC' ),
    ),
) );

// A value inside the first row of a repeater called "specs". The second
// argument is the path below the field.
$q = new WP_Query( array(
    'post_type'  => 'product',
    'meta_query' => array(
        array( 'key' => nik_meta_key( 'specs', '0_name' ), 'value' => 'weight' ),
    ),
) );

// Any depth works: a subfield of a repeater nested inside another repeater.
nik_meta_key( 'sections', '0_items_1_label' );

// Ordering by a field.
$q = new WP_Query( array(
    'post_type' => 'product',
    'meta_key'  => nik_meta_key( 'price' ),
    'orderby'   => 'meta_value_num',
    'order'     => 'DESC',
) );