WordPress:如何使用 jQuery 从自定义分类中获取自定义字段的元数据

WordPress: How to get metadata of Custom Fields from Custom Taxonomy with using jQuery

我已将自定义 Post 字段(复选框列表)添加到自定义分类 'product_cat'。

我的自定义 Post 类型 ('product') Add/Edit 页面上也有一个包含此自定义分类法 ('product_cat') 的下拉列表。

当自定义分类法下拉列表发生变化时,如何使用 jQuery 从这些自定义字段中获取元数据?

    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('#prodcatoptions').change(function() {
                var productsubcut = jQuery('#prodcatoptions').val();
                if ( productsubcut == '') {
                } else {               
                    var data = {

                        /* I don't know what I need to type here */

                    };
                    jQuery.post(ajaxurl, data, function(response){
                        console.log(response);
                    });
                }    
            });
        });
    </script>

为此,您必须向 wordpress 后端发出 ajax 请求。例如:

在后端,您的 functions.php 文件中将包含以下函数

<?php

function get_custom_meta() {
  global $post; // This only works for admin site
   
  $meta_key = $_GET['key']; # 'key' is the value of the option selected on the selected 

  $data = get_post_meta( $post->ID, $meta_key, true ); # true returns a single value
  echo $data;
  exit;
}
add_action( 'wp_ajax_get_custom_meta', 'get_custom_meta' );
?>

这将 return 有关所选分类的元数据。

按如下方式更改您的 javascript:

<script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery('#prodcatoptions').change(function() {
                var productsubcut = jQuery('#prodcatoptions').val();
                if ( productsubcut == '') {
                } else {               
                    var data = {

                       action: 'get_custom_meta',
                       key: productsubcut
                    };
                    jQuery.get(ajaxurl, data, function(response){
                        console.log(response);
                    });
                }    
            });
        });
    </script>