在wordpress上我想创建一个帖子模板,如果用户点击链接,它将通过ajax加载自定义字段值。我在这里发现了一个插件How to load the custom field values of the post via ajax in wordpress,但下载链接似乎已经死了所以我无法下载:(任何人都可以帮我编码吗?我不是程序员,所以告诉我最简单的解决方案
答案 0 :(得分:2)
在functions.php文件中
<?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();
?>
在您的模板中,您将获得如下链接(请记住在类get_meta_val的链接中有postid和metakey属性)
<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>