46. Types de champs personnalisés | Field Forge - Champs personnalisés, conçus pour la vitesse
Télécharger Se connecter

46. Types de champs personnalisés

Créez vos propres types de champs en étendant le système de types de champs de Field Forge.

Enregistrement d’un type de champ personnalisé

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();
} );

Utilisation du type de champ personnalisé

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 );

Assistant IA Forge En ligne

Bonjour ! Je suis l'assistant IA Field Forge. Posez-moi n'importe quelle question sur le plugin — configuration, fonctionnalités, dépannage ou développement.

À l'instant
Propulsé par Forge IA · Parcourir la documentation