javascript - 如何访问或将 php 变量传递给 JavaScript?
问题描述
我是 Stackoverflow 的新手,对 WordPress 也比较陌生。我一直在尝试构建一个自定义 WordPress 主题,它还允许您在 WordPress 仪表板中插入类别的图像。到目前为止,我已经能够使用以下代码将图像 URL 保存到数据库中:
update_term_meta($term_id, 'custom_image_data', $image_data);
($image_data 是一个包含以下元素的数组:图像的 ID 和 URL)
但是,现在我想检索这两条信息并将它们与我对应的 Javascript 文件共享。到目前为止,我有这个代码:
function image_uploader_js() {
wp_register_script('image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload'));
wp_enqueue_script('image_file_uploader_js');
wp_localize_script('image_file_uploader_js', 'customUploads', array('imageData' => get_term_meta(get_queried_object_id(), 'custom_image_data', true)) ); //**
}
add_action('admin_footer', 'image_uploader_js');
但是,当我进入 Google Chrome 控制台并输入 CustomUploads 时,它只会显示一个空字符串。但是,如果我将代码get_queried_object_id()替换为静态数字 1(对应于类别的 $term_id),我会得到 CustomUploads { id: ##, URL: HTTPS://..... } 这是想要的结果。
我的问题是为什么原始代码不起作用,我如何能够与我的 Javascript 文件共享 id 和 URL 或我的类别图像?
解决方案
确保您在类别页面上,然后 get_queried_object_id() 将返回术语 ID。在其他页面中,您将获得与该页面对应的不同 ID。
您可以使用is_category()
来检查您是否在类别页面上。
function image_uploader_js() {
if( is_category() ){
wp_register_script('image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload'));
wp_enqueue_script('image_file_uploader_js');
wp_localize_script('image_file_uploader_js', 'customUploads', array('imageData' => get_term_meta(get_queried_object_id(), 'custom_image_data', true)) ); //**
}
}
add_action('admin_footer', 'image_uploader_js');
或者您可以获取所有术语并推送到一个数组,然后您可以访问 js 文件。
function image_uploader_js() {
$category = get_terms( array(
'taxonomy' => 'category', // your custom taxonomy name
'hide_empty' => false
) );
$imageData = array();
if( !empty( $category ) ){
foreach ( $category as $key => $cat ) {
$imageData[$cat->term_id] = get_term_meta( $cat->term_id, 'custom_image_data', true );
}
}
wp_register_script( 'image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload') );
wp_enqueue_script( 'image_file_uploader_js');
wp_localize_script( 'image_file_uploader_js', 'customUploads', array( 'imageData' => $imageData ) ); //**
}
add_action('admin_footer', 'image_uploader_js');
推荐阅读
- python - 为什么这个 if/else 语句中的这些布尔表达式没有按预期计算?
- cooja - Contiki NG/Cooja - 无根节点的非 RPL 模拟
- wordpress - 在社交媒体上共享一个 wordpress 网站时,它很快就会显示出来,但该网站是实时的。有什么建议吗?
- javascript - 删除引号和第一个字母之间的空格
- sockets - 当我调用新方法时,JavaFX FadeTransition 结束其他 SetVisbilities 停止工作
- python - 如何使用 Elbow 方法获得自组织地图“SOM”的最佳 K?
- arrays - GCC 11 在不使用字符串操作时给出 -Wstringop-overflow
- sql - how to pass a list into postgres as a parameter
- docker - 带有子域的反向代理 nginx docker 容器
- flutter - 有人知道如何在条形码中存储许多值吗?