Forked from ajskelton/WP Customizer - Image Control
Last active
November 21, 2019 23:24
-
-
Save Asikur22/2fd9e72c9dc477d1bf7a8a8057294b9e to your computer and use it in GitHub Desktop.
Add a Image Field to WP Customizer
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