0

I have an image upload field in theme-customizer :

/* Background Image */
$wp_customize->add_setting(
    'tcx_background_image',
    array(
        'default'      => '',
        'transport'    => 'postMessage',
        'sanitize_callback'  => 'is_image',
    )
);

And sanitize-callback function :

function is_image( $input ) {
if(getimagesize($input)){   
    return esc_url_raw($input);     
}else{
        return '';  
     }
}

This part works correctly :

I click Select Image button and then I select my image inside Media Library and I click Choose Image and finally i click Save&Publish and my image is outputted correctly (Nothing wrong thus far)

Here is the dreaded alert problem ( Happens when clicking X button in Customizer ):

Now I want to Remove my image so I click Remove button and now there is no image, then I click Save&Publish button.

The problem arises when I click X (EXIT) button inside Customizer because it triggers an alert box "The changes you made will be lost if you navigate away from this page.Are you sure you want to leave this page?".

I have enabled define('WP_DEBUG', true); if set it to false the alert is gone,also if I set my 'sanitize_callback' => 'esc_url_raw', the alert is also gone it happens only if I use my custom function is_image();

So how can I remove that alert box when using custom function?

This is js file for customize-preview if that helps... THX!!

wp.customize( 'tcx_background_image', function( value ) {
    value.bind( function( to ) {

        0 === $.trim( to ).length ?
            $( 'body' ).css( 'background-image', '' ) :
            $( 'body' ).css( 'background-image', 'url( ' + to + ')' );

    });
});
0

Ok i solved it looks like that getimagesize will generate error/notice if image is not found, so alert box will fire...

This is straight from PHP docs:

If accessing the filename image is impossible getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Here is the solution that worked for me:

function is_image( $input ) {
   if ( !empty($input) && getimagesize($input)) {
     return esc_url_raw($input);
   } else {
    return '';
   }
}

If somebody has a better solution please let me know...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.