以下是场景:
- 一个类别中有几个产品(products表示特定类别)
- 每个产品(帖子)都有几个图片(我通过添加自定义字段)
- 在前端,产品将一起显示
- 在该页面上,页脚中将有一个图像滑块
- 单击每个产品名称,将更改滑块图像根据点击的产品
因此,我所需要的只是获得与单击的产品相对应的自定义字段值。使用AJAX请求可以做到这一点吗。?这样我就可以在没有回复的情况下管理所有这些过程。
谢谢。
我没有wordpress的经验,但我可以向您展示AJAX的示例。
据我所知,你必须在点击相关帖子或产品时调用ajax函数。
<script>
jQuery(document).ready(function () {
jQuery("#PRODCUTID").click(function () {
jQuery.ajax({
type : "POST"
,url :"YOUR_URL_ON_WHICH_YOU_PUT_LOGIC_TO_FETCH_IDS_FOR_SLIDER"
,data :"CLICKED_PRODUCT_ID="+CLICKED_PRODUCT_ID // this the variable which will be posted and will find it (particular URL which you passed) on the controller action or in view file
,success : function(data){
//YOUR CODE HERE WHICH IS REPLACING PRODUCT ID
}
,beforeSend: function(html){
//some kind of loader or text mean while data is waiting for the response
},
});
})
})
</script>
希望这将有所帮助,并随时要求任何AJAx请求。
这很容易。当然,感谢Rajat Modi在ajax方面的帮助。给你:
将其添加到模板文件中的functions.php中:
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/myajax.js', array('jquery'), 1.0 ); // jQuery will be included automatically
// get_template_directory_uri() . '/js/script.js'; // Inside a parent theme
// get_stylesheet_directory_uri() . '/js/script.js'; // Inside a child theme
// plugins_url( '/js/script.js', __FILE__ ); // Inside a plugin
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_stuff' ); // ajax for not logged in users
function ajax_action_stuff()
{
$post_id = $_POST['post_id']; // getting variables from ajax post
// doing ajax stuff
$custom_fields = get_post_custom($post_id);
$imageurlset = $custom_fields['images'];
$urlstring = $imageurlset[0];
$imageurl = explode(',', $urlstring);
//update_post_meta($post_id, 'post_key', 'meta_value');
exit(json_encode($imageurl)); // stop executing script
}
创建以下代码并将其添加到"/js/script.js"中:
$(document).ready(
function() {
$('.prduct_name').click(function () {
$('.spcl_content').find('.prduct_name').removeClass("selected");
$(this).addClass("selected");
var ithis = $(this);
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: ithis.attr("id")
}, function(data) {
var number_of_images = data.length;
//console.log(data);
var image_link="";
for(var i=0; i<number_of_images; i++)
{
var image_url = data[i];
image_link = image_link+'<li><a href="'+image_url+'" rel="scroller" target="temp_win"><img src="'+image_url+'"/></a></li>'
}
//console.log(image_link); // alerts 'ajax submitted'
var starting='<div class="wt-scroller"><div class="prev-btn"></div><div class="slides"><ul class="slider_mania">';
var ending='</ul></div><div class="next-btn"></div><div class="lower-panel"></div></div>';
var total=starting+image_link+ending;
//console.log(total);
$(".container_carol").html(total).fadeIn("slow");
},"json");
return false;
});
我希望现在已经清楚了。再次感谢我的朋友的回复。祝你今天过得愉快。:)