Wordpress:在 ajax 中加载自定义字段 [英] Wordpress: Load custom field in ajax
问题描述
在 wordpress 上,我想制作一个帖子模板,如果用户点击链接,它将通过 ajax 加载自定义字段值.我在这里找到了一个插件 如何在 wordpress 中通过 ajax 加载帖子的自定义字段值 但下载链接似乎已失效,所以我无法下载 :( 谁能帮我编写代码?我不是程序员,所以告诉我最简单的解决方案
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
推荐答案
在functions.php文件中
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();
?>
在您的模板中,您将拥有如下链接(记住在类 get_meta_val 的链接中具有 postid 和 metakey 属性)
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>
这篇关于Wordpress:在 ajax 中加载自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!