我写了一个代码,该代码根据访问者的位置生成链接,并且运行得很好,但是我发现生成的代码被缓存了,因为我使用的是全页缓存,因此尽管可以解决该问题,但我可以使用ajax来加载该链接。我使用了下面的代码,这些代码在获取一些我需要的变量(例如位置变量和链接域变量等)时效果很好。但是,我无法获取WooCommerce自定义字段数据,甚至无法返回空白的产品ID。>
我正在使用此代码获取自定义字段,当直接在函数中使用该自定义字段时,效果很好,但是无法在ajax中运行
$uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );
我在functions.php中使用了该代码
add_action( 'woocommerce_before_add_to_cart_button', 'affiliate_link_ajax', 11);
function affiliate_link_ajax() {
?>
<script>
jQuery(document).ready(function(){
jQuery.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: 'POST',
data: {
action: 'getmyfunctionform1'
},
dataType: 'html',
success: function(response) {
jQuery("#myResultsform1").html(response);
}
});
});
</script>
<!-- end Ajax call to getmyfunctionform1 smc 11-22-2013 -->
<div id="myResultsform1"></div>
<?php
}
以及funnctions.php中的这段代码
// Ajax Function to Load PHP Function myfunctionform1 smc 11/22/2013
add_action('wp_ajax_getmyfunctionform1', 'myfunctionform1');
add_action('wp_ajax_nopriv_getmyfunctionform1', 'myfunctionform1');
function myfunctionform1() {
$uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );
echo $uk_asin;
// Whatever php and or html you want outputed by the ajax call in template file
die(); } // important must use
// end Ajax Function to Load PHP Function myfunctionform1 smc 11/22/2013
如果答案很简单,我将不胜感激,因为我还是编码新手。
答案 0 :(得分:3)
将您的帖子ID传递给您的AJAX请求:
data: {
action: 'getmyfunctionform1',
postId: <?php echo get_post()->ID; ?>
}
然后在回调函数中使用它来获取元值:
function myfunctionform1() {
$postId = filter_input( INPUT_POST, 'postId', FILTER_SANITIZE_NUMBER_INT );
$uk_asin = get_post_meta( $postId, "wccaf_uk_asin", true );
// etc.
}