I have noticed that WP_Customize_Image_Control does indeed return the
filename instead of the ID, but this is only for images.
That’s because the class extends WP_Customize_Upload_Control
which has the type set to upload
:
class WP_Customize_Upload_Control extends WP_Customize_Media_Control {
public $type="upload";
public $mime_type="";
...
}
And for Customizer controllers using the above class, the JavaScript controller is wp.customize.UploadControl
which saves the file URL instead of the attachment ID.
So if you want to save the URL instead of the ID, then you could either:
-
Extend
WP_Customize_Upload_Control
:class myUploadControl extends WP_Customize_Upload_Control { ... }
-
Or when you add the control, pass an instance of
WP_Customize_Upload_Control
:$wp_customize->add_control( new WP_Customize_Upload_Control( $wp_customize, 'your_setting', array( 'label' => 'Label Here', 'section' => 'section_id', ... ) ) );
Note:
$wp_customize
is an instance of theWP_Customize_Manager
class.
But if you have to save the ID, but need to get the URL dynamically in JavaScript, then you could for example use wp.apiRequest()
to make an API request to /wp/v2/media/<media ID>
:
wp.customize( 'your_setting', function( value ) {
value.bind( function( to ) {
wp.apiRequest( { path: '/wp/v2/media/' + to } )
.then( function ( s ) {
console.log( s.source_url ); // logs the full URL to the file
// do your thing
} );
} );
} );