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

46. Пользовательские типы полей

Создайте свои собственные типы полей, расширяя систему типов полей Field Forge.

Регистрация пользовательского типа поля

php
add_action( 'fieldforge/register_field_types', function() {
    class FIELDFORGE_Field_Type_Star_Rating {

        public function __construct() {
            add_filter( 'fieldforge/field_types', [ $this, 'register' ] );
            add_filter( 'fieldforge/render_field/type=star_rating', [ $this, 'render' ], 10, 2 );
            add_filter( 'fieldforge/format_value/type=star_rating', [ $this, 'format' ], 10, 3 );
        }

        public function register( $types ) {
            $types['star_rating'] = [
                'label'    => 'Star Rating',
                'category' => 'basic',
                'defaults' => [
                    'max_stars' => 5,
                ],
            ];
            return $types;
        }

        public function render( $field, $value ) {
            $max = $field['max_stars'] ?? 5;
            $current = intval( $value );
            echo '<div class="ff-star-rating" data-max="' . $max . '">';
            for ( $i = 1; $i <= $max; $i++ ) {
                $active = $i <= $current ? ' active' : '';
                echo '<span class="star' . $active . '" data-value="' . $i . '">&#9733;</span>';
            }
            echo '<input type="hidden" name="' . esc_attr( $field['name'] ) . '" value="' . esc_attr( $current ) . '">';
            echo '</div>';
        }

        public function format( $value, $field, $post_id ) {
            return intval( $value );
        }
    }

    new FIELDFORGE_Field_Type_Star_Rating();
} );

Использование пользовательского типа поля

php
// In a field group definition
FIELDFORGE_Field_Groups::instance()->create( [
    'title'  => 'Review Fields',
    'fields' => [
        [
            'key'       => 'field_review_rating',
            'label'     => 'Rating',
            'name'      => 'rating',
            'type'      => 'star_rating',
            'max_stars' => 5,
        ],
    ],
    'location_rules' => [
        [ [ 'param' => 'post_type', 'operator' => '==', 'value' => 'review' ] ],
    ],
] );

// In a template
$rating = get_field( 'rating' ); // Returns integer, e.g., 4
echo str_repeat( '&#9733;', $rating ) . str_repeat( '&#9734;', 5 - $rating );

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

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

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