The following code shows how to create a shortcode which will load and display an external file.
This can be used anywhere shortcodes are supported – for example posts, pages, widget areas.
In this example we’ll be using http://example.com/file.txt
It uses the built-in WordPress functions to safely retrieve the file (wp_remote_get) and display it (esc_html).
How do I use this?
Copy the code below into either your theme’s functions.php file – or into your custom functions plugin.
Insert the shortcode where you want the external file displayed
[remote_show_file url=”http://example.com/file.txt”]
View the page – and the external file should be displayed.
The code
/*
* Load external url in shortcode
* IT Support GUides - www.itsupportguides.com
* 11/05/2019
*/
function gg_remote_show_file( $atts ) {
// normalize attribute keys, lowercase
$atts = array_change_key_case( ( array )$atts, CASE_LOWER );
// override default attributes with user attributes
$shortcode_attributes = shortcode_atts(
array(
'url' => '', // default url
), $atts );
$url = esc_attr( $shortcode_attributes['url'] );
if ( $url ) { // if we have a url
// request remote url
$request = wp_remote_get( $url, array( 'timeout' => 120 ) );
// if there is an error - return nothing
if( is_wp_error( $request ) ) {
return;
}
// get response body
$data = wp_remote_retrieve_body( $request );
if( $data !== false ) { // if we have a response body
return esc_html( $data ); // return content
}
}
}
add_shortcode( 'remote_show_file', 'gg_remote_show_file' );