When it comes to working with remote requests on the server side, the file_get_contents() function seems to be a reliable option, but WordPress already includes an exceptionally useful API called HTTP API.
The HTTP API can be used for sending data to and retrieving data from remote APIs, and that also means any requests to your own server.
There are four primary functions that comprise the HTTP API in WordPress:
For instance, you could use wp_remote_get() to retrieve data from the network.json file and then parse it along with the wp_localize_script() function, exposing the data you need to your enqueued js file.
Please take as a reference the following function (not tested), but you should not have any issues with it.
-- The Function --
function wp_request_localize_my_json_data() {
// Helpers to define the $url path
//$protocol = is_ssl() ? 'https' : 'http';
$directory = trailingslashit( get_template_directory_uri() );
// Define the URL
$url = $directory . 'network.json';
// Register main js file to be enqueued
wp_register_script( 'network-js', $directory . 'assets/js/network.js', array('jquery'), false, true );
// Make the request
$request = wp_remote_get( $url );
// If the remote request fails, wp_remote_get() will return a WP_Error, so let’s check if the $request variable is an error:
if( is_wp_error( $request ) ) {
return false; // Bail early
}
// Retrieve the data
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
// Localize script exposing $data contents
wp_localize_script( 'network-js', 'networkJSON', array(
'network_url' => admin_url( 'admin-ajax.php' ),
'full_data' => $data
)
);
// Enqueues main js file
wp_enqueue_script( 'network-js' );
}
add_action( 'wp_enqueue_scripts', 'wp_request_localize_my_json_data', 10);
If everything goes right, you'll probably end up with the localized data retrieved from the network.json file at your disposal.
Now let's suppose you have a variable named current_user in the network.json file. So in order to access this variable within your enqueued JS file, you would simply do:
<script type="text/javascript">
var my_data = networkJSON.full_data;
var user = my_data.current_user;
</script>