Wordpress: Load custom field in ajax

2019-06-12 23:59发布

问题:

On wordpress I want to make a post template where if a user clicks on a link it will load the custom field value via ajax. I found a plugin here How to load the custom field values of the post via ajax in wordpress but the download link seems to be dead so I'm unable to download :( can anyone help me code? I'm not a programmer so tell me the easiest solution

回答1:

In functions.php file

<?php

add_action('wp_ajax_load_custom_field_data','load_custom_field_data');
add_action('wp_ajax_nopriv_load_custom_field_data','load_custom_field_data');

function load_custom_fields_data(){
$postid=$_POST['postid'];
$metakey= $_POST['metakey'];
echo get_post_meta($postid,$metakey,true);
die();

?>

In your template where you will have your link like below(remember to have postid and metakey attributes in the links with class get_meta_val)

<a class="get_meta_val" postid="<?php echo $post->ID?>" metakey ="your_meta_key">Get Custom Value</a>
//get postid in any way you want and put you customfield name in your_meta_key

<script type="text/javascript">
jQuery(document).ready(function(e) {
    jQuery(document).one('click','.get_meta_val',function(e){
        e.preventDefault();
        var pid = jQuery(this).attr('postid');
        var metakey = jQuery(this).attr('metakey');
        var data = {
            'action': 'load_custom_field_data',
            'postid': pid,
            'metakey':metakey
        };
        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            alert('Custom Field Value is: ' + response);
            //Here you can do whatever you want with your returned value
        });
        });
});
</script>