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

问题描述:

我已将自定义帖子字段"(复选框列表)添加到自定义分类法"product_cat"中.

I have added Custom Post Fields (a list of check-boxes) to the Custom Taxonomy 'product_cat'.

我的自定义帖子类型"(产品")添加/编辑"页面上还包含一个此自定义分类"("product_cat")的下拉列表.

Also I have a drop-down with this Custom Taxtonimies ('product_cat') on my Custom Post Type ('product') Add/Edit page.

当自定义分类"下拉列表更改时,如何使用jQuery从这些自定义字段"中获取元数据?

How I can get a metadata from these Custom Fields with using jQuery when the Custom Taxonomy drop-down was changed?

    <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请求.例如:

In order to do that, you will have to issue an ajax request to the wordpress backend. For example:

在后端,您的functions.php文件中将具有以下功能

In the backend you will have the following function in your functions.php file

<?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' );
?>

这将返回有关所选分类法的元数据.

This will return the metadata about the selected taxonomy.

按如下所示更改您的JavaScript:

Change your javascript as follows:

<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>