WooCommerce在类别页面的弹出窗口中显示追加销售的产品



在分类页面上,当用户点击"添加到购物车"按钮时,我希望在弹出窗口中显示与该特定产品相关的追加销售产品,以便用户可以选择将追加销售产品与该产品一起添加到购物车中。

<script>
jQuery(function() {
    jQuery(".single_add_to_cart_button, .add_to_cart_button").click(function(evt) {
        //evt.preventDefault();
        var product_id = jQuery(this).attr("data-product_id");
        jQuery.ajax({
            type: "POST",
            url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
            data: {action: 'myajax-submit', id: product_id},
            cache: false,
            success: function(data) {
                jQuery("#result").html(data);
            }
        });
        //return false;
    })
})

在functions.php中,我编写了以下代码
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit(){
  $product_id = $_REQUEST['id'];
}

在探索插件核心文件后,我自己解决了这个问题。下面是代码片段,可以帮助寻找相同

的人。
$product = new WC_Product($product_id);
    $upsells = $product->get_upsells();
   if (!$upsells)
        return;
$meta_query = WC()->query->get_meta_query();
    $args = array(
        'post_type' => 'product',
        'ignore_sticky_posts' => 1,
        'no_found_rows' => 1,
        'posts_per_page' => $posts_per_page,
        'orderby' => $orderby,
        'post__in' => $upsells,
        'post__not_in' => array($product->id),
        'meta_query' => $meta_query
    );
    $products = new WP_Query($args);
    if ($products->have_posts()) :
// Iterate over the each product
   endif;