Fields
Creating field types
<?php
namespace HivePress\Fields;
use HivePress\Helpers as hp;
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
class Foo_Bar extends Field {
// Declare the field properties.
protected $max_length;
// Set the property defaults.
public function __construct( $args = [] ) {
$args = hp\merge_arrays(
[
'max_length' => 123,
],
$args
);
parent::__construct( $args );
}
// Do something after the field is loaded.
protected function boot() {
if ( $this->max_length ) {
$attributes['maxlength'] = $this->max_length;
}
parent::boot();
}
// Normalize the field value.
public function normalize() {
parent::normalize();
if ( ! is_null( $this->value ) ) {
$this->value = trim( wp_unslash( $this->value ) );
}
}
// Sanitize the field value.
public function sanitize() {
$this->value = sanitize_text_field( $this->value );
}
// Validate the field value.
public function validate() {
if ( parent::validate() && strlen( $this->value ) > $this->max_length ) {
$this->add_errors( 'Custom error message' );
}
return ! $this->errors;
}
// Render the field HTML.
public function render() {
return '<input type="text" name="' . esc_attr( $this->name ) . '" value="' . esc_attr( $this->value ) . '" ' . hp\html_attributes( $this->attributes ) . '>';
}
}
Customizing field types
Last updated