首页 文章

在Wordpress中使用Ajax加载模板部分

提问于
浏览
0

您好我正在尝试向我的商店添加一项功能,当有人点击产品而不是重定向到产品页面时,产品页面会在主页中加载ajax,就像在本网站中一样(点击其中一个产品): http://www.itsjustyes.com . 这是我的jquery:

jQuery(document).ready(function($){


$('.info_btn').on('click',function(){

    var theId = $(this).attr('id');


   var div = $('#product-container')
    $.post('wp-admin/admin-ajax.php',{
        action:'my_get_posts',post_id: theId
    }, function(data){
        console.log(data);
       div.html(data);
    })
    return false;
});

});

这是我在functions.php中的代码:

//Ajax call to product

function my_get_posts_return(){

global $post;


$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);

if ($post_id > 0) {

    $the_query = new WP_query(array('p' => $post_id));
    if ($the_query->have_posts()) {
        while ($the_query->have_posts()) : $the_query->the_post();

            wc_get_template_part( 'content', 'single-product' );

        endwhile;
     } else {
        echo "There were no posts found";
    }
}


wp_die();

}

add_action('wp_ajax_my_get_posts','my_get_posts_return'); add_action('wp_ajax_nopriv_my_get_posts','my_get_posts_return');

我一直认为在循环中没有找到任何帖子,这很奇怪,因为我知道我发送了正确的帖子ID . 顺便说一句,如果我尝试用get_the_title($ post_id)获取产品页面的各个部分,我就可以了 . 只有当我尝试使用循环加载模板部分时才会遇到此问题 . 知道我做错了什么?

1 回答

  • 1

    您的WP_Query找不到正确的帖子类型 .

    $the_query = new WP_query(array('p' => $post_id));
    

    上面的查询根本没有返回任何帖子 . 默认情况下,wordpress会假设您正在查询post_type ='posts',这就是您无法找到产品帖子的原因 . 因此,您需要指定要查找的post_type . 使用WooCommerce产品,您可以使用:

    $the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
    

    附:使用wp_localize_script函数注册你的ajaxurl是一个很好的做法,而不是在你的javascript中硬编码 . 您可以按照this post了解更多详情 .

    希望这可以帮助 .

相关问题