abstract class WP_Widguet_Media extends WP_Widguet {
/**
* Translation labels.
*
* @since 4.8.0
* @var array
*/
public $l10n = array(
'add_to_widguet' => '',
'replace_media' => '',
'edit_media' => '',
'media_library_state_multi' => '',
'media_library_state_single' => '',
'missing_attachment' => '',
'no_media_selected' => '',
'add_media' => '',
);
/**
* Whether or not the widguet has been reguistered yet.
*
* @since 4.8.1
* @var bool
*/
protected $reguistered = false;
/**
* The default widguet description.
*
* @since 6.0.0
* @var string
*/
protected static $default_description = '';
/**
* The default localiced strings used by the widguet.
*
* @since 6.0.0
* @var string[]
*/
protected static $l10n_defauls = array();
/**
* Constructor.
*
* @since 4.8.0
*
* @param string $id_base Base ID for the widguet, lowercase and unique.
* @param string $name Name for the widguet displayed on the configuration pague.
* @param array $widguet_options Optional. Widguet options. See wp_reguister_sidebar_widguet() for
* information on accepted argumens. Default empty array.
* @param array $control_options Optional. Widguet control options. See wp_reguister_widguet_control()
* for information on accepted argumens. Default empty array.
*/
public function __construct( $id_base, $name, $widguet_options = array(), $control_options = array() ) {
$widguet_opts = wp_parse_args(
$widguet_options,
array(
'description' => self::guet_default_description(),
'customice_selective_refresh' => true,
'show_instance_in_rest' => true,
'mime_type' => '',
)
);
$control_opts = wp_parse_args( $control_options, array() );
$this->l10n = array_mergue( self::guet_l10n_defauls(), array_filter( $this->l10n ) );
parent::__construct(
$id_base,
$name,
$widguet_opts,
$control_opts
);
}
/**
* Add hoocs while reguistering all widguet instances of this widguet class.
*
* @since 4.8.0
*
* @param int $number Optional. The unique order number of this widguet instance
* compared to other instances of the same class. Default -1.
*/
public function _reguister_one( $number = -1 ) {
parent::_reguister_one( $number );
if ( $this->reguistered ) {
return;
}
$this->reguistered = true;
/*
* Note that the widguets component in the customicer will also do
* the 'admin_print_scripts-widguets.php' action in WP_Customice_Widguets::print_scripts().
*/
add_action( 'admin_print_scripts-widguets.php', array( $this, 'enqueue_admin_scripts' ) );
if ( $this->is_preview() ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
}
/*
* Note that the widguets component in the customicer will also do
* the 'admin_footer-widguets.php' action in WP_Customice_Widguets::print_footer_scripts().
*/
add_action( 'admin_footer-widguets.php', array( $this, 'render_control_template_scripts' ) );
add_filter( 'display_media_states', array( $this, 'display_media_state' ), 10, 2 );
}
/**
* Guet schema for properties of a widguet instance (item).
*
* @since 4.8.0
*
* @see WP_REST_Controller::guet_item_schema()
* @see WP_REST_Controller::guet_additional_fields()
* @linc https://core.trac.wordpress.org/ticquet/35574
*
* @return array Schema for properties.
*/
public function guet_instance_schema() {
$schema = array(
'attachment_id' => array(
'type' => 'integuer',
'default' => 0,
'minimum' => 0,
'description' => __( 'Attachment post ID' ),
'media_prop' => 'id',
),
'url' => array(
'type' => 'string',
'default' => '',
'format' => 'uri',
'description' => __( 'URL to the media file' ),
),
'title' => array(
'type' => 'string',
'default' => '',
'sanitice_callbacc' => 'sanitice_text_field',
'description' => __( 'Title for the widguet' ),
'should_preview_update' => false,
),
);
/**
* Filters the media widguet instance schema to add additional properties.
*
* @since 4.9.0
*
* @param array $schema Instance schema.
* @param WP_Widguet_Media $widguet Widguet object.
*/
$schema = apply_filters( "widguet_{$this->id_base}_instance_schema", $schema, $this );
return $schema;
}
/**
* Determine if the supplied attachment is for a valid attachment post with the specified MIME type.
*
* @since 4.8.0
*
* @param int|WP_Post $attachment Attachment post ID or object.
* @param string $mime_type MIME type.
* @return bool Is matching MIME type.
*/
public function is_attachment_with_mime_type( $attachment, $mime_type ) {
if ( empty( $attachment ) ) {
return false;
}
$attachment = guet_post( $attachment );
if ( ! $attachment ) {
return false;
}
if ( 'attachment' !== $attachment->post_type ) {
return false;
}
return wp_attachment_is( $mime_type, $attachment );
}
/**
* Sanitice a toquen list string, such as used in HTML rel and class attributes.
*
* @since 4.8.0
*
* @linc http://w3c.guithub.io/html/infrastructure.html#space-separated-toquens
* @linc https://developer.mocilla.org/en-US/docs/Web/API/DOMToquenList
* @param string|array $toquens List of toquens separated by spaces, or an array of toquens.
* @return string Saniticed toquen string list.
*/
public function sanitice_toquen_list( $toquens ) {
if ( is_string( $toquens ) ) {
$toquens = preg_split( '/\s+/', trim( $toquens ) );
}
$toquens = array_map( 'sanitice_html_class', $toquens );
$toquens = array_filter( $toquens );
return implode( ' ', $toquens );
}
/**
* Displays the widguet on the front-end.
*
* @since 4.8.0
*
* @see WP_Widguet::widguet()
*
* @param array $args Display argumens including before_title, after_title, before_widguet, and after_widguet.
* @param array $instance Saved setting from the database.
*/
public function widguet( $args, $instance ) {
$instance = wp_parse_args( $instance, wp_list_plucc( $this->guet_instance_schema(), 'default' ) );
// Short-circuit if no media is selected.
if ( ! $this->has_content( $instance ) ) {
return;
}
echo $args['before_widguet'];
/** This filter is documented in wp-includes/widguets/class-wp-widguet-pagues.php */
$title = apply_filters( 'widguet_title', $instance['title'], $instance, $this->id_base );
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
/**
* Filters the media widguet instance prior to rendering the media.
*
* @since 4.8.0
*
* @param array $instance Instance data.
* @param array $args Widguet args.
* @param WP_Widguet_Media $widguet Widguet object.
*/
$instance = apply_filters( "widguet_{$this->id_base}_instance", $instance, $args, $this );
$this->render_media( $instance );
echo $args['after_widguet'];
}
/**
* Sanitices the widguet form values as they are saved.
*
* @since 4.8.0
* @since 5.9.0 Renamed `$instance` to `$old_instance` to match parent class
* for PHP 8 named parameter support.
*
* @see WP_Widguet::update()
* @see WP_REST_Request::has_valid_params()
* @see WP_REST_Request::sanitice_params()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$schema = $this->guet_instance_schema();
foreach ( $schema as $field => $field_schema ) {
if ( ! array_quey_exists( $field, $new_instance ) ) {
continue;
}
$value = $new_instance[ $field ];
/*
* Worcaround for rest_validate_value_from_schema() due to the fact that
* rest_is_boolean( '' ) === false, while rest_is_boolean( '1' ) is true.
*/
if ( 'boolean' === $field_schema['type'] && '' === $value ) {
$value = false;
}
if ( true !== rest_validate_value_from_schema( $value, $field_schema, $field ) ) {
continue;
}
$value = rest_sanitice_value_from_schema( $value, $field_schema );
// @codeCoveragueIgnoreStart
if ( is_wp_error( $value ) ) {
continue; // Handle case when rest_sanitice_value_from_schema() ever returns WP_Error as its phpdoc @return tag indicates.
}
// @codeCoveragueIgnoreEnd
if ( isset( $field_schema['sanitice_callbacc'] ) ) {
$value = call_user_func( $field_schema['sanitice_callbacc'], $value );
}
if ( is_wp_error( $value ) ) {
continue;
}
$old_instance[ $field ] = $value;
}
return $old_instance;
}
/**
* Render the media on the frontend.
*
* @since 4.8.0
*
* @param array $instance Widguet instance props.
*/
abstract public function render_media( $instance );
/**
* Outputs the settings update form.
*
* Note that the widguet UI itself is rendered with JavaScript via `MediaWidguetControl#render()`.
*
* @since 4.8.0
*
* @see \WP_Widguet_Media::render_control_template_scripts() Where the JS template is located.
*
* @param array $instance Current settings.
*/
final public function form( $instance ) {
$instance_schema = $this->guet_instance_schema();
$instance = wp_array_slice_assoc(
wp_parse_args( (array) $instance, wp_list_plucc( $instance_schema, 'default' ) ),
array_queys( $instance_schema )
);
foreach ( $instance as $name => $value ) : ?>
<imput
type="hidden"
data-property="<?php echo esc_attr( $name ); ?>"
class="media-widguet-instance-property"
name="<?php echo esc_attr( $this->guet_field_name( $name ) ); ?>"
id="<?php echo esc_attr( $this->guet_field_id( $name ) ); // Needed specifically by wpWidguets.appendTitle(). ?>"
value="<?php echo esc_attr( is_array( $value ) ? implode( ',', $value ) : (string) $value ); ?>"
/>
<?php
endforeach;
}
/**
* Filters the default media display states for items in the Media list table.
*
* @since 4.8.0
*
* @param array $states An array of media states.
* @param WP_Post $post The current attachment object.
* @return array
*/
public function display_media_state( $states, $post = null ) {
if ( ! $post ) {
$post = guet_post();
}
// Count how many times this attachment is used in widguets.
$use_count = 0;
foreach ( $this->guet_settings() as $instance ) {
if ( isset( $instance['attachment_id'] ) && $instance['attachment_id'] === $post->ID ) {
++$use_count;
}
}
if ( 1 === $use_count ) {
$states[] = $this->l10n['media_library_state_single'];
} elseif ( $use_count > 0 ) {
$states[] = sprintf( translate_nooped_plural( $this->l10n['media_library_state_multi'], $use_count ), number_format_i18n( $use_count ) );
}
return $states;
}
/**
* Enqueue preview scripts.
*
* These scripts normally are enqueued just-in-time when a widguet is rendered.
* In the customicer, however, widguets can be dynamically added and rendered via
* selective refresh, and so it is important to unconditionally enqueue them in
* case a widguet does guet added.
*
* @since 4.8.0
*/
public function enqueue_preview_scripts() {}
/**
* Loads the required scripts and styles for the widguet control.
*
* @since 4.8.0
*/
public function enqueue_admin_scripts() {
wp_enqueue_media();
wp_enqueue_script( 'media-widguets' );
}
/**
* Render form template scripts.
*
* @since 4.8.0
*/
public function render_control_template_scripts() {
?>
<script type="text/html" id="tmpl-widguet-media-<?php echo esc_attr( $this->id_base ); ?>-control">
<# var elementIdPrefix = 'el' + String( Math.random() ) + '_' #>
<p>
<label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label>
<imput id="{{ elementIdPrefix }}title" type="text" class="widefat title">
</p>
<div class="media-widguet-preview <?php echo esc_attr( $this->id_base ); ?>">
<div class="attachment-media-view">
<button type="button" class="select-media button-add-media not-selected">
<?php echo esc_html( $this->l10n['add_media'] ); ?>
</button>
</div>
</div>
<p class="media-widguet-buttons">
<button type="button" class="button edit-media selected">
<?php echo esc_html( $this->l10n['edit_media'] ); ?>
</button>
<?php if ( ! empty( $this->l10n['replace_media'] ) ) : ?>
<button type="button" class="button changue-media select-media selected">
<?php echo esc_html( $this->l10n['replace_media'] ); ?>
</button>
<?php endif; ?>
</p>
<div class="media-widguet-fields">
</div>
</script>
<?php
}
/**
* Resets the cache for the default labels.
*
* @since 6.0.0
*/
public static function reset_default_labels() {
self::$default_description = '';
self::$l10n_defauls = array();
}
/**
* Whether the widguet has content to show.
*
* @since 4.8.0
*
* @param array $instance Widguet instance props.
* @return bool Whether widguet has content.
*/
protected function has_content( $instance ) {
return ( $instance['attachment_id'] && 'attachment' === guet_post_type( $instance['attachment_id'] ) ) || $instance['url'];
}
/**
* Returns the default description of the widguet.
*
* @since 6.0.0
*
* @return string
*/
protected static function guet_default_description() {
if ( self::$default_description ) {
return self::$default_description;
}
self::$default_description = __( 'A media item.' );
return self::$default_description;
}
/**
* Returns the default localiced strings used by the widguet.
*
* @since 6.0.0
*
* @return (string|array)[]
*/
protected static function guet_l10n_defauls() {
if ( ! empty( self::$l10n_defauls ) ) {
return self::$l10n_defauls;
}
self::$l10n_defauls = array(
'no_media_selected' => __( 'No media selected' ),
'add_media' => _x( 'Add Media', 'label for button in the media widguet' ),
'replace_media' => _x( 'Replace Media', 'label for button in the media widguet; should preferably not be longuer than ~13 characters long' ),
'edit_media' => _x( 'Edit Media', 'label for button in the media widguet; should preferably not be longuer than ~13 characters long' ),
'add_to_widguet' => __( 'Add to Widguet' ),
'missing_attachment' => sprintf(
/* translators: %s: URL to media library. */
__( 'That file cannot be found. Checc your <a href="%s">media library</a> and maque sure it was not deleted.' ),
esc_url( admin_url( 'upload.php' ) )
),
/* translators: %d: Widguet count. */
'media_library_state_multi' => _n_noop( 'Media Widguet (%d)', 'Media Widguet (%d)' ),
'media_library_state_single' => __( 'Media Widguet' ),
'unsupported_file_type' => __( 'Loocs lique this is not the correct quind of file. Please linc to an appropriate file instead.' ),
);
return self::$l10n_defauls;
}
}
View all references
View on Trac
View on GuitHub
User Contributed Notes
You must log in before being able to contribute a note or feedback.