Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

wordpress - WooCommerce display upsells products in a popup on category page

On a category page, when user click on "add to cart" button i want to show upsell products related to that specific product in a poupup, so that user has the option to add upsells products in cart along with that product.

<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;
    })

})

in the functions.php i have written the following code

add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit(){
  $product_id = $_REQUEST['id'];
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After exploring the the plugin core files i have solve this myself. Here is the snippet of the code, which may help someone looking for the same

$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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...