2017-04-10 18 views
1

背景 我在用户将页面保存在Wordpress后端时动态创建数据的JSON文件。我通过钩子'save_post'并使用file_put_contents将文件'network.json'保存到我的主题文件夹的根目录中。我这样做是为了让我可以访问我主题中的js脚本中的特定数据。访问Wordpress主题中的本地JSON文件

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

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

上述是否正确,技术上最合理?

其他方法我以前排队通过一个脚本,并设置适当的AJAX功能以admin-ajax.php调用使用AJAX在WordPress的

。这似乎过于复杂,我的需求。

我也可以设置一个js变量我的模板文件中像下面:

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

本地化脚本是实现它的方法!请参阅文档[这里](https://codex.wordpress.org/Function_Reference/wp_localize_script)。您可以使用可供其他js文件访问的本地化数据排入脚本。答案[这里](http://stackoverflow.com/a/5229483/3406865)是我正在采取的方法。 – Celso

回答

2

当谈到与服务器端的远程请求工作时,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); 

如果一切发展顺利,你可能会在您的处置从network.json文件检索到的本地化数据结束。

现在让我们假设您在network.json文件中有一个名为current_user的变量。所以为了在入队的JS文件中访问这个变量,你只需要做:

<script type="text/javascript"> 
    var my_data = networkJSON.full_data; 
    var user = my_data.current_user; 
</script> 
+0

感谢@adriano伟大的方法。我没有考虑使用HTTP API,因为我在自己的服务器上工作,但是有道理。一个问题是如何避免在这里使用绝对URL'$ url =''。 $协议。 '://example.com/wp-content/themes/ihdf/network.json';' – Celso

+0

嗨@Celso - 对不起,** $ url **变量是肉'$ url = $ directory 。 'network.json';' - 假定文件存在于你主题的主目录中。您也可以将其更改为任何其他路径,例如'$ url = $ directory。 'dynamic_data/network/network.json';' - 这又假设这些目录也存在于你的主题的主目录中。我更新了代码以反映它。 –