Celso
Celso

Reputation: 605

Access a local JSON file in Wordpress Theme

Background I am dynamically creating a JSON file of data when a user saves a page in the Wordpress backend. I'm doing this through the hook 'save_post' and saving the file 'network.json' using file_put_contents to the root of my theme folder. I'm doing this so I can access specific data from a js script in my theme.

Current Approach I have a js file enqueued into my theme with the following JS inside of it. The below is working but I'm wondering if it is the best approach for calling a local JSON file within a WP theme.

$.getJSON( "../wp-content/themes/ihdf/network.json", function(data) {
    console.log(data);
});

Is the above the proper and most technically sound way of doing it?

Other Approaches

I've previously used ajax in Wordpress by enqueuing a script and setting up the proper ajax function to call with admin-ajax.php. That seems overly complicated for my needs.

I could also set a js variable within my template file like the below:

var networkJSON = <?php get_template_directory_uri() . '/network.json' ?>

Upvotes: 5

Views: 21575

Answers (2)

saber tabatabaee yazdi
saber tabatabaee yazdi

Reputation: 4959

if you want to read json file in wordpress via plugin or theme, use this function.

function get_local_file_contents( $file_path ) {
    ob_start();
    include $file_path;
    $contents = ob_get_clean();

    return $contents;
}

tonight i want to read a json file in json folder beside my php file in plugin and find this article

i cant do it with file_get_contents()

Upvotes: 1

Adriano Monecchi
Adriano Monecchi

Reputation: 1200

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>

Upvotes: 7

Related Questions