当谈到与服务器端的远程请求工作时,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>
本地化脚本是实现它的方法!请参阅文档[这里](https://codex.wordpress.org/Function_Reference/wp_localize_script)。您可以使用可供其他js文件访问的本地化数据排入脚本。答案[这里](http://stackoverflow.com/a/5229483/3406865)是我正在采取的方法。 – Celso