背景 当用户在 Wordpress 后端保存页面时,我正在动态创建一个 JSON 数据文件。我通过 Hook “save_post”执行此操作,并使用 file_put_contents 将文件“network.json”保存到我的主题文件夹的根目录。我这样做是为了可以从主题中的 js 脚本访问特定数据。
当前方法 我有一个 js 文件排队到我的主题中,其中包含以下 JS。下面的工作正常,但我想知道这是否是在 WP 主题中调用本地 JSON 文件的最佳方法。
$.getJSON( "../wp-content/themes/ihdf/network.json", function(data) {
console.log(data);
});
以上是正确且技术上最合理的方法吗?
其他方法
我以前在 Wordpress 中使用过 ajax,方法是将脚本排入队列并设置适当的 ajax 函数以调用 admin-ajax.php。这对我的需求来说似乎过于复杂。
我还可以在我的模板文件中设置一个 js 变量,如下所示:
var networkJSON = <?php get_template_directory_uri() . '/network.json' ?>
最佳答案
在服务器端处理远程请求时,file_get_contents()
函数似乎是一个可靠的选择,但 WordPress 已经包含一个非常有用的 API,称为 HTTP API。 .
HTTP API 可用于向远程 API 发送数据和从远程 API 检索数据,这也意味着对您自己的服务器的任何请求。
WordPress 中的 HTTP API 包含四个主要函数:
- wp_remote_get() – 用于从端点检索数据
- wp_remote_post() – 用于将数据发送到端点
- wp_remote_head() – 用于发送 HEAD 请求
- wp_remote_retrieve_body() – 用于从服务器响应中检索主体内容
例如,您可以使用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>
关于php - 在 Wordpress 主题中访问本地 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328595/