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',
) );
Ми використовуємо файли cookie та подібні технології для аналітики сайту й реклами (Google, Meta). Оберіть, чи дозволяти їх. Політика конфіденційності
