在Wordpress主题中访问本地JSON文件

Cel*_*lso 3 php ajax wordpress json

背景 我在用户在Wordpress后端保存页面时动态创建数据的JSON文件.我正在通过钩子'save_post'执行此操作并使用file_put_contents将文件'network.json'保存到我的主题文件夹的根目录.我这样做,所以我可以从我的主题中的js脚本访问特定数据.

当前的方法 我有一个js文件排入我的主题,其中包含以下JS.以下是工作,但我想知道它是否是在WP主题中调用本地JSON文件的最佳方法.

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

以上是适当且技术最合理的方式吗?

其他方法

我以前在Wordpress中使用ajax,通过将脚本排队并设置正确的ajax函数来调用admin-ajax.php.这似乎对我的需求过于复杂.

我也可以在我的模板文件中设置一个js变量,如下所示:

var networkJSON = <?php get_template_directory_uri() . '/network.json' ?>
Run Code Online (Sandbox Code Playgroud)

Adr*_*chi 5

当在服务器端处理远程请求时,该file_get_contents()函数似乎是一个可靠的选项,但WordPress已经包含一个非常有用的API,称为HTTP API.

HTTP API可用于向远程API发送数据和从远程API检索数据,这也意味着对您自己的服务器的任何请求.

在WordPress中有四个主要功能构成HTTP API:

例如,您可以使用wp_remote_get()network.json文件中检索数据,然后将其与wp_localize_script()函数一起解析,从而将您需要的数据暴露给排队的js文件.

请将以下功能作为参考(未经测试),但您不应该遇到任何问题.

- 功能 -

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);
Run Code Online (Sandbox Code Playgroud)

如果一切顺利,您可能最终会得到从network.json文件中检索到的本地化数据.

现在让我们假设你有一个current_usernetwork.json文件中命名的变量.因此,为了在您排队的JS文件中访问此变量,您只需执行以下操作:

<script type="text/javascript">
    var my_data = networkJSON.full_data;
    var user = my_data.current_user;
</script>
Run Code Online (Sandbox Code Playgroud)