$this->block_type->get_max_files(),
'max_size' => $this->block_type->get_max_size(),
);
}
/**
* @return Attributes_Trait
*/
public function files() {
if ( is_null( $this->files ) ) {
$this->files = new class() {
use Attributes_Trait;
};
}
return $this->files;
}
protected function render_previews(): string {
$files = $this->block_type->block_attrs['default'];
if ( empty( $files ) ) {
return '';
}
$preview = $this->get_preview_html();
$html = '';
foreach ( $files as $file ) {
if (
empty( $file['url'] ) &&
isset( $file['id'] ) &&
is_array( $file['id'] )
) {
$file = $file['id'];
}
$file_url = isset( $file['url'] ) ? $file['url'] : wp_get_attachment_url( $file );
$updated = str_replace( '%file_url%', $file_url, $preview );
$updated = str_replace(
'%file_name%',
$this->get_name_from_file( $file['url'] ),
$updated
);
// preset field
$updated = str_replace( '', $this->get_field_preset( $file ), $updated );
$image_ext = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'svg', 'webp', 'avif' );
$img_ext_preg = '!\.(' . join( '|', $image_ext ) . ')$!i';
if ( preg_match( $img_ext_preg, $file['url'] ) ) {
$replace = sprintf( '
', $file['url'] );
$updated = str_replace( '', $replace, $updated );
}
$html .= $updated;
}
return $html;
}
private function get_name_from_file( string $file_url ): string {
$parts = explode( '/', $file_url );
return end( $parts );
}
protected function get_preview_html(): string {
ob_start();
require Tools::get_global_template( 'fields/image-preview.php' );
return ob_get_clean();
}
protected function get_field_preset( array $file ): string {
ob_start();
require Tools::get_global_template( 'fields/preset-media-field.php' );
return ob_get_clean();
}
public function render( $wp_block = null, $template = null ) {
$this->files()->add_attribute(
'data-args',
htmlspecialchars(
Tools::encode_json( $this->get_block_args() )
)
);
$field = parent::render( $wp_block, $template );
$template = sprintf(
'%s',
$this->get_preview_html()
);
return ( $template . $field );
}
}