首页 文章

WordPress:如何使用jQuery从Custom Taxonomy获取自定义字段的元数据

提问于
浏览
0

我已将Custom Post Fields(复选框列表)添加到Custom Taxonomy'product_cat' .

此外,我在自定义帖子类型('产品')添加/编辑页面上有这个自定义Taxtonimies('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>

1 回答

  • 1

    为此,您必须向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' );
    ?>
    

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

    更改您的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>
    

相关问题