首页 > 解决方案 > 如何访问或将 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 或我的类别图像?

标签: javascriptphpwordpress

解决方案


确保您在类别页面上,然后 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');

推荐阅读