Last active
October 21, 2021 22:32
-
-
Save ajskelton/4916e1a93327e77961c17585d1a96686 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$wp_customize->add_setting( 'themeslug_media_setting_id', array( | |
'sanitize_callback' => 'absint', | |
'validate_callback' => 'themeslug_validate_image, | |
) ); | |
$wp_customize->add_control( | |
new WP_Customize_Media_Control( $wp_customize, 'themeslug_media_setting_id', array( | |
'label' => __( 'Custom Core Media Setting' ), | |
'section' => 'custom_section', // Add a default or your own section | |
'mime_type' => 'image', | |
) ) ); | |
function themeslug_validate_image( $validity, $value ) { | |
// Get the url of the image | |
$image = wp_get_attachment_image_src( $value )[0]; | |
/* | |
* Array of valid image file types. | |
* | |
* The array includes image mime types that are included in wp_get_mime_types() | |
*/ | |
$mimes = array( | |
'jpg|jpeg|jpe' => 'image/jpeg', | |
'gif' => 'image/gif', | |
'png' => 'image/png', | |
'bmp' => 'image/bmp', | |
'tif|tiff' => 'image/tiff', | |
'ico' => 'image/x-icon' | |
); | |
// Return an array with file extension and mime_type. | |
$file = wp_check_filetype( $image, $mimes ); | |
if( !$value ) { | |
// If no image has been chosen, instruct user to choose an image | |
$validity->add( 'required', __( 'Please choose an image' ) ); | |
} elseif ( !$file['ext'] ) { | |
// If a valid image file extension is not found, instruct user to choose appropriate image | |
$validity->add( 'not_valid', __( 'Please choose a valid image type' ) ); | |
} | |
return $validity; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment