Table Field Add-on for ACF and SCF

Описание

Плагин Table Field является дополнением и расширяет функциональность плагинов Advanced Custom Fields (ACF) и Secure Custom Fields с помощью удобных для редактирования таблиц.

Для работы этого плагина требуются плагины Advanced Custom Fields или Secure Custom Fields!

Поле таблицы также работает с повторителем ACF, гибкими типами полей и поддерживает ACF блоки для Gutenberg

Возможности

  • Заголовок таблицы (опционально)
  • Подпись таблицы (опционально)
  • Поддержка ACF Gutenberg блоков
  • Добавление и удаление столбцов и строк таблицы
  • Изменение порядка столбцов и строк путем перетаскивания
  • Для перехода к редактору следующих ячеек нажмите клавишу: tab
  • Для перехода к редактору предыдущих ячеек нажмите клавиши: shift + tab

Переводы

  • Английский — по умолчанию, всегда доступен
  • Немецкий: Deutsch — immer dabei!
  • Датский: Dansk — altid der!
  • Польский: Polski — zawsze tam jest!

Примечание: Пожалуйста, переведите плагин на свой язык, чтобы сделать его еще более полезным.

PRO

There is also a Table Field Pro Add-on for the Advanced Custom Fields and Secure Custom Fields plugins.

  • Настройка пользовательской таблицы по умолчанию
  • Настройка минимального и максимального количества строк и столбцов
  • Настройка выбора стиля для таблицы и её частей
  • Функционал ограничения редактирования таблицы
  • Опциональный настраиваемый редактор WordPress для редактирования содержимого ячеек
  • Строки заголовка (thead) и подвала (tfoot) таблицы
  • Столбец-заглушка
  • Объединение строк и стообцов
  • Улучшенный способ перемещения строк и столбцов
  • Отключение перемещения отдельных столбцов
  • Поддержка REST-API
  • Поддержка WP GraphQL
  • Поддержка сторонних плагинов

Pro версия плагина может работать параллельно, и при необходимости вы можете изменить существующее поле с типом «Таблица» на поле с типом «Таблица Pro».

to the plugin website

Скриншоты

  • Настройки поля

  • Редактирование контента поля

  • Захватите строки и столбцы в серой области и перетащите их.

Установка

Это программное обеспечение можно использовать как плагин для WP, так и для включения в тему.
Однако обновления будут доступны только после активации в качестве плагина.

Плагин

  1. Скопируйте папку «advanced-custom-fields-table-field» в вашу папку с плагинами.
  2. Активируйте плагин на административной странице плагинов.

Часто задаваемые вопросы

Как вывести таблицу HTML?

To render the table fields data as an html table in one of your template files (page.php, single.php) you can start with the following basic code example:

$table = get_field( 'your_table_field_name' );

if ( ! empty ( $table ) ) {

    echo '<table>';

        if ( ! empty( $table['caption'] ) ) {

            echo '<caption>' . $table['caption'] . '</caption>';
        }

        if ( ! empty( $table['header'] ) ) {

            echo '<thead>';

                echo '<tr>';

                    foreach ( $table['header'] as $th ) {

                        echo '<th>';
                            echo $th['c'];
                        echo '</th>';
                    }

                echo '</tr>';

            echo '</thead>';
        }

        echo '<tbody>';

            foreach ( $table['body'] as $tr ) {

                echo '<tr>';

                    foreach ( $tr as $td ) {

                        echo '<td>';
                            echo $td['c'];
                        echo '</td>';
                    }

                echo '</tr>';
            }

        echo '</tbody>';

    echo '</table>';
}

Поле таблицы не возвращает данные при вызове get_field()?

If the table has only one empty cell, then get_field() returns FALSE. get_field() returns NULL when a field is not stored in the database. That happens when a page is copied but not their fields content. You can check both with empty()

$table = get_field( 'your_table_field_name' );

if ( ! empty( $table ) ) {
    // $table is not FALSE and not NULL.
    // Field exists in database and has content.
}

Как справиться с разрывами линии?

This is about displaying line breaks in the admin tables and getting line breaks as <br> when outputting the tables HTML.

Преобразование переносов строки для HTML вывода

To convert line breaks to <br> in tables HTML output the PHP function nl2br() can be used:

For line breaks in table header cells replace…

echo $th['c'];

с…

echo nl2br( $th['c'] );

For line breaks in table body cells replace…

echo $td['c'];

с…

echo nl2br( $td['c'] );

Отображение разрывов строк при редактировании таблиц

To display natural line breaks in the editing tables in the admin area, add the following styles to the admin area.

.acf-table-header-cont,
.acf-table-body-cont {
    white-space: pre-line;
}

One way to add these styles to the WordPress admin area is adding the following code to your functions.php file of the theme.

add_action('admin_head', 'acf_table_styles');

function acf_table_styles() {
  echo '<style>
    .acf-table-header-cont,
    .acf-table-body-cont {
        white-space: pre-line;
    }
  </style>';
}

How to use the table field in Elementor or other Page Builders?

In general, its up to the page builder plugins to support ACF field types. But because the table field is not a native ACF field, the support for this field may never happen in page builders.

For now the way to go is using a shortcode. Elementor provides for example a shortcode widget. Before you can use a shortcode to display a table fields table, you have to setup a shortcode in functions.php. The following code does this. You can modify the table html output for your needs.

function shortcode_acf_tablefield( $atts ) {

    $param = shortcode_atts( array(
        'field-name' => false,
        'subfield-name' => false,
        'post-id' => false,
        'table-class' => '',
    ), $atts );

    $class = new class( $param ) {

        public $atts;

        public $field_names;

        public $field_data = '';

        public $html = '';

        public function __construct( $atts ) {

            if ( is_string( $atts['subfield-name'] ) ) {

                $atts['field-name'] = $atts['subfield-name'];
            }

            if ( ! is_string( $atts['field-name'] ) ) {

                return '';
            }

            $this->atts = $atts;

            $this->field_names = explode( '/', $this->atts['field-name'] );

            $this->subfield( 0 );

        }

        private function may_get_table_html( $data ) {

            if ( isset( $data['body'] ) ) {

                $return = '<table class="' . $this->atts['table-class'] . '">';

                    if ( ! empty( $data['caption'] ) ) {

                        echo '<caption>' . $data['caption'] . '</caption>';
                    }

                    if ( $data['header'] ) {

                        $return .= '<thead>';

                            $return .= '<tr>';

                                foreach ( $data['header'] as $th ) {

                                    $return .= '<th>';
                                        $return .= $th['c'];
                                    $return .= '</th>';
                                }

                            $return .= '</tr>';

                        $return .= '</thead>';
                    }

                    $return .= '<tbody>';

                        foreach ( $data['body'] as $tr ) {

                            $return .= '<tr>';

                                foreach ( $tr as $td ) {

                                    $return .= '<td>';
                                        $return .= $td['c'];
                                    $return .= '</td>';
                                }

                            $return .= '</tr>';
                        }

                    $return .= '</tbody>';

                $return .= '</table>';

                $this->html .= $return;
            }
        }

        private function subfield( $level = 0, $data = null ) {

            if ( isset( $data['body'] ) ) {

                $this->may_get_table_html( $data );

                return;
            }
            else if ( ! isset( $this->field_names[ $level ] ) ) {

                return;
            }
            else if ( $data === null ) {

                if ( $this->atts['subfield-name'] === false ) {

                    $data = get_field(  $this->field_names[0],  $this->atts['post-id'] );
                }
                else {

                    $data = get_sub_field( $this->field_names[0] );
                }
            }
            else if ( isset( $data[ $this->field_names[ $level ] ] ) ) {

                $data = $data[ $this->field_names[ $level ] ];
            }

            // repeater/group field
            if (
                is_array( $data ) &&
                isset( $data[0] ) &&
                ! isset( $data[0]['acf_fc_layout'] )
                ) {

                if ( is_numeric( $this->field_names[ $level + 1 ] )  ) {

                    if ( isset( $data[  $this->field_names[ $level + 1 ] ] ) ) {

                        $this->subfield( $level + 1, $data[  $this->field_names[ $level + 1 ] ] );
                    }
                }
                else {

                    foreach( $data as $key => $item ) {

                        $this->subfield( $level + 1, $item );
                    }
                }
            }

            // flexible content field
            else if (
                is_array( $data ) &&
                isset( $data[0] ) &&
                isset( $data[0]['acf_fc_layout'] )
                ) {

                foreach( $data as $key => $item ) {

                    if (
                        $item['acf_fc_layout'] === $this->field_names[ $level + 1 ] &&
                        isset( $item[ $this->field_names[ $level + 2 ] ] )
                    ) {

                        $this->subfield( $level + 2, $item[ $this->field_names[ $level + 2 ] ] );
                    }
                }
            }

            // table field
            else {

                $this->subfield( $level + 1, $data );
            }
        }
    };

    return $class->html;
}

add_shortcode( 'tablefield', 'shortcode_acf_tablefield' );

Then use the shortcode with the corresponding shortcode options of the Page Builder.

Getting a table field from the current page or post

[tablefield field-name="table_field_name"]

Getting a table field from a group field

[tablefield field-name="group_field_name/table_field_name"]

Getting a table field from a repeater field

[tablefield field-name="repeater_field_name/table_field_name"]

Получение поля таблицы из определенного элемента поля repeater

[tablefield field-name="repeater_field_name/item_index/table_field_name"]

Getting a table field from a flexible content field

[tablefield field-name="flexible_content_field_name/layout_name/table_field_name"]

Вы также можете получить поле таблицы из любого типа вложенных полей, как показано в данном примере, где поле таблицы является частью макета поля гибкого содержимого, которое, в свою очередь, является подполем поля повторителя, которое, в свою очередь, является подполем поля группы.

[tablefield field-name="group_field_name/repeater_field_name/flexible_content_field_name/layout_name/table_field_name"]

Получение поля таблицы из цикла group, repeater или flexible content field

[tablefield subfield-name="table_field_name"]

Получение поля таблицы из другой страницы или записи

[tablefield field-name="table_field_name" post-id="123"]

Получение поля таблицы со страницы параметров ACF

[tablefield field-name="table_field_name" post-id="option"]

Добавление CSS-класса к HTML-элементу таблицы

[tablefield field-name="table_field_name" table-class="my-table-style"]

Обновление таблицы с помощью update_field()

You can use the ACF PHP function update_field() to change a tables data.

Уведомление

  • Make sure that the number of entries in the header array matches the number of cells in the body rows.
  • The array key ‘c’ stands for the content of the cells to have the option of adding other cell setting in future development.
  • The table data obtained by get_field() are formatted and differ by the original database data obtained by get_post_meta().

Example of changing table data using get_field() and update_field()

// the post ID where to update the table field
$post_id = 123;

$table_data = get_field( 'my_table', $post_id );

$table_data = array(
    'use_header' => true, // boolean true/false
    'caption' => 'My Caption',
    'header' => array(
        0 => array(
            'c' => 'A',
        ),
        1 => array(
            'c' => 'B',
        ),
    ),
    'body' => array(
        0 => array(
            0 => array(
                'c' => 'The content of first cell of first row',
            ),
            1 => array(
                'c' => 'The content of second cell of first row',
            ),
        ),
        1 => array(
            0 => array(
                'c' => The content of first cell of second row',
            ),
            1 => array(
                'c' => 'The content of second cell of second row',
            ),
        ),
    )
);

update_field( 'my_table', $table_data, $post_id );

Пример добавления новой строки

// the post ID where to update the table field
$post_id = 123;

// gets the table data
$table_data = get_field( 'my_table', $post_id );

// defines the new row and its columns
$new_row = array(

    // must define the same amount of columns as exists in the table

    // column 1
    array(
        // the 'c' stands for content of the cell
        'c' => 'Cell Content of Column 1',
    ),

    // column 2
    array(
        'c' => 'Cell Content of Column 2',
    )
);

// adds the new row to the table body data
array_push( $table_data['body'], $new_row );

// saves the new table data
update_field( 'my_table', $table_data, $post_id );

Проблемы сторонних плагинов

Since version 1.3.1 of the table plugin, the storing format of the table data changes from JSON string to serialized array for new or updated tables. The issue with JSON is because of third party plugins that do not properly applying wp_slash() to a post_meta value before updating with update_post_metadata(). This can break JSON strings because update_post_metadata() removes backslashes by default. Backslashes are part of the JSON string syntax escaping quotation marks in content.

The table field plugin prevents broken JSON strings to save as a table field data and throws an error message that explains the issue. But this may also breaks the functionality of the third party plugin trying to update the table data. You could disable the JSON string check in the table field plugin using the following code in the wp-config.php file. But then the table JSON data are no longer protected from destroing by update_post_metadata(). Use the following code in wp-config.php only, if you understand the risk…

define( "ACF_TABLEFIELD_FILTER_POSTMETA", false );

Настройки очистки UI

Начиная с версии 1.3.33 вы можете настраивать параметры очистки данных UI.

Для этого необходимо добавить скрипт в очередь как административный скрипт ACF. Вы можете добавить его в очередь в файле functions.php вашей темы, используя следующее действие.

add_action( 'acf/input/admin_enqueue_scripts', function() {

    wp_enqueue_script(
        'table-field-config', // Table field config script handle
        get_template_directory_uri() . '/js/table-field-config.js', // Path to the script in the theme
    );
});

Очистка UI полей таблицы осуществляется с помощью DOMPurify.
Для изменения параметров DOMPurify воспользуйтесь следующим хуком поля таблицы в скрипте конфигурации поля таблицы.

document.addEventListener('tableFieldRegisterHooks', function(){

    ACFTableField.addFilter( 'core', 'sanitize_html', function( options ) {

        // DOMPurify Options, @see: https://github.com/cure53/DOMPurify?tab=readme-ov-file#can-i-configure-dompurify

        return options;
    });
});

Отзывы

05.05.2025 2 ответа
On production you can should have debug mode disabled anyway but in development this plugin is causing an issue on first activation. Every save action in the admin causes a white screen with the _load_textdomain_just_in_time was called to early. You need to manually go back everytime to continue your work.Kind regards
26.03.2025
As the title says, brilliant function for a table, making it more streamline for the end user. If available I’d rate more, the support has been amazing. Getting the table to work for a different page builder, that I can now use going forward on many other projects is awesome. Thanks again for the help.
07.01.2025
I needed a table field for my headless CMS. Although this plugin works okay, it would be nice if it had WPGraphQL support by default. I had to modify my functions file in order to register the ACF field and query the table.
07.03.2023
I just came back to using this plugin today after having it installed some years ago on a site. Still a wonderfully clean, simple and flexible Table field solution, thank you! 👍🏻
Посмотреть все 60 отзывов

Участники и разработчики

«Table Field Add-on for ACF and SCF» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:

Участники

«Table Field Add-on for ACF and SCF» переведён на 12 языков. Благодарим переводчиков за их работу.

Перевести «Table Field Add-on for ACF and SCF» на ваш язык.

Заинтересованы в разработке?

Посмотрите код, проверьте SVN репозиторий, или подпишитесь на журнал разработки по RSS.

Журнал изменений

1.3.35

  • Обновление библиотеки DOMPurify до версии 3.3.3 для устранения уязвимости, связанных с межсайтовым скриптированием (XSS).

1.3.34

  • Разрешает атрибут target=»_blank» в ссылках
  • Добавляет фильтр, который обеспечивает автоматическое присвоение атрибута rel=»noopener» ссылкам, использующим target=»_blank»

1.3.33

  • Добавляет хук, регистрирующий событие «tableFieldRegisterHooks»
  • Внесены изменения и исправления в пример, демонстрирующий, как добавить в очередь административный скрипт и применить фильтр «sanitize_html».

1.3.32

  • Добавляет базовую поддержку Polylang
  • Позволяет загружать и выполнять административный скрипт между скриптом инициализации плагинов и скриптом выполнения для использования Javascript хуков плагинов
  • Добавляет Javascript фильтр для опций DOMPurify
  • Добавляет очистку надписи таблицы
  • Исправление неуникальных ID HTML-элементов

1.3.31

  • Adds sanitizing table data using wp_kses( $data, ‘post’ ) during update_field().
  • Fixes a Cross-Site Scripting vulnerability in table cell content exploitable by authenticated users with Author-level access or higher.
  • Исправлены незначительные проблемы со стилем редактора ячеек таблицы.

1.3.30

  • Позволяет использовать update_field() для полей пользователя

1.3.29

  • Исправлено отсутствующее изображение предварительного просмотра поля.

1.3.28

  • Исправлена загрузка переводов с translate.wordpress.org

1.3.27

  • Исправлена ранняя загрузка текстового домена плагина.

1.3.26

  • Добавляет автоматическое восстановление таблицы. Исправляет данные таблицы при загрузке из базы данных и при редактировании таблицы.

1.3.24

  • Исправляет схему REST API

1.3.23

  • Добавляет схему REST API

1.3.22

  • Fixes an issue where the trigger changed was executed to the field without any actual change to the field.
  • Fixes an issue where changes to the order of rows and columns and new rows and columns were not saved.

1.3.21

  • Добавляет поддержку функции update_field() для страниц настроек
  • Исправлено отсутствие свойства «use_header» в функции get_field()

1.3.20

  • Исправлено некоторое количество ошибок при регистрации событий в Gutenberg
  • Исправлена проблема, из-за которой таблица редактирования не загружалась при первом запуске

1.3.19

  • Fixes issue not initial loading editing tables in Gutenberg blocks.

1.3.18

  • Fixes issue with Gutenberg block containing a table field. If the same block was used multiple times on a page, the changes were not saved.

1.3.17

  • Changes registering the ACF field type using the acf_register_field_type methode.
  • Прекращает поддержку ACF версии 4.

1.3.16

  • Исправлена логическая ошибка, вызывавшая PHP предупреждения

1.3.15

  • Исправляет проблему с count() в PHP8

1.3.14

  • Prevents the font-size and line-height in the blue editor window of the table cells from being overwritten by other styles.
  • Fixes an issue in update_field() where setting the «use_header» option to false did not work.

1.3.13

  • Fixes missing sortable columns and rows in ACF Gutenberg blocks
  • Обновляет устаревший функционал jQuery

1.3.12

  • Обновление стилей ACF кнопок плюс и минус

1.3.11

  • Добавляет поддержку обновления типа термина с помощью функции update_field()

1.3.10

  • Fixes table cell content and caption update issue on ACF Gutenberg blocks
  • Replaces jQuery depricated size() methode by .length property

1.3.9

  • Исправлена ошибка, приводящая к некорректному отображению стилей полей выбора ACF в WordPress 5.3.
  • Fixes an issue when adding or removing columns using update_field().

1.3.8

  • Fixes an issue where the option «use header» was not applied on updating a field with update_field().
  • Fixes an issue where percent characters in a table field content causes an JavaScript error.

1.3.7

  • Fixes an issue where the table header was not displayed on a page preview.

1.3.6

  • Fixes an issue when changing the field type to table of a field that already has content in the database from another field type.

1.3.5

  • Fixes an issue that removes table header content using update_field() while option «use header» is set to «no».
  • Исправлена проблема с фильтром update_post_metadata

1.3.4

  • Fixes an issue that prevents the removal of table contents

1.3.3

  • Fixes returning empty table after saving content containing a single quote.

1.3.2

  • Fixes returning empty table after saving content containing quotes
  • Исправлена проблема, возникавшая при использовании функции update_field() для поля таблицы

1.3.1

  • Changes table data storing format from JSON string to serialized array. This is due to an issue caused by third party plugins using update_post_meta() without providing wp_slash() to the value before. Existing table data values in JSON string format in the database will still exists and be compatible. When a field is saved again, the storage format changes from JSON to serialized array.
  • Исправляет ошибку PHP в подписи таблицы

1.3.0

  • Добавляет поддержку подписи таблицы
  • Исправлена проблема с JavaScript для ACF версии 4

1.2.7

  • Adds PHP constant ACF_TABLEFIELD_FILTER_POSTMETA. Setting this constant to false prevents an update_post_metadata filter looking for tablefield JSON strings destroyed by update_post_meta().

1.2.6

  • Заменяет метод jQuery.noConflict
  • Prevents PHP error if table fields value is from a previous fieldtype

1.2.5

  • Добавлен датский перевод, благодарим Jeppe Skovsgaard

1.2.4

  • Исправлена проблема с обратной косой чертой при использовании update_field();

1.2.3

  • Adds support for the ACF update_field() function. If you get the table fields data array by get_field(), you can change the table data array and using update_field() to save the changes to the field.

1.2.2

  • Adds plugin version to table data for handling structural changes.
  • Fixes loosing table data containing quotes on third party update_post_meta() actions to table field values. Limited to new fields or fields value changed since plugin version 1.2.2.
  • Исправлено PHP предупреждение, возникающее начиная с версии PHP 7.2, когда данные body имеют значение null

1.2.1

  • Исправлена ошибка, из-за которой при переводе не учитывались языковые настройки пользователя
  • Adds description for handling line breaks to plugins page

1.2

  • Adds support for tab navigation. Uses shift + tab for backward navigation.
  • Незначительные улучшения кода

1.1.16

  • Keeps the WordPress admin area working, if tablefields value is not a valid JSON string. Logs the invalid value in the console for debugging.

1.1.15

  • Добавляет польский перевод от Pawel Golka

1.1.14

  • Fixes table does not appear under certain field groups location rules

1.1.13

  • Исправлена XSS уязвимость на страницах /wp-admin/

1.1.12

  • Добавлена поддержка правил таксономии для групп полей

1.1.11

  • Исправлено повторное прорисовывание таблиц при изменении другого контента

1.1.10

  • Исправлена функциональность таблиц с учетом правил ACF

1.1.9

  • Fixes returning false on single empty table cell for ACF version 4

1.1.8

  • Исправлена поддержка страниц редактирования пользователей

1.1.7

  • Исправляет поддержку страниц профиля пользоватя

1.1.6

  • Пользовательский интерфейс: Устранена проблема с отключением заголовка таблицы

1.1.5

  • Fixes issue occured after database migration with plugin «WP Migrate DB»

1.1.4

  • Takes over icon class changes in ACF-Pro since version 5.3.2

1.1.3

  • Исправлено неверное название функции «change_template»

1.1.2

  • Исправлено отсутствие таблицы при изменении шаблона страницы

1.1.1

  • Совместимость с изменениями значков в версии ACF Pro 5.2.8
  • Исправление высоты верхней легенды таблицы в FireFox
  • Исправляет положение иконки удаления столбца в IE

1.1

  • Improved User Experience when deleting all columns and rows.
  • Совместимость с обновлениями ACF Pro версии 5.2.7.

1.0.7

  • Use wp_json_encode() instead of json_encode(). This may fix issues in rare enviroments.

1.0.6

  • If the table has only a single empty cell (this is by default), no table data will return now.

1.0.5

  • Исправляет проблему JavaScript в IE 8.
  • Fixes missing table borders and table header´s height in FireFox.

1.0.4

  • Устраняет проблему с URI на некоторых хостах.

1.0.3

  • Исправляет ошибку PHP в HTTP_REFFERER.

1.0.2

  • Fixes error when including the plugin from inside a theme.

1.0.1

  • Fixes ACF validation error «required» when header option «use table header» was used and unchecked.

1.0

  • Официальный релиз бесплатной версии