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

▼魔方 西西 提交于 2019-12-11 11:10:43

问题


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

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

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>

回答1:


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

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.

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>


来源:https://stackoverflow.com/questions/36747463/wordpress-how-to-get-metadata-of-custom-fields-from-custom-taxonomy-with-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!