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
268 views
in Technique[技术] by (71.8m points)

Getting product_id - Woocommerce - Ajax pop-up

I have this code below, but just don't seem to managed to get "product_id" into html to show the right product. Can somebody point me into the right direction?

I'm new to Ajax, so just don't know how to fetch data from ajax into html.

How could I get "product_id" into this form: < div > echo $product_id < /div > ?

<script>
jQuery(document).ready(function($) {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
    modal.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
// Let's do the magic
    // make sure to change #myBtn to read more button selector
    $('.products > li .add_to_cart_button').click(function(e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    // get url
        var url = $(this).attr('href');
        var container = $('#myModal').find('.popup');
        var data = {
            action: 'show_product',
            url: url,

        };
        $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
           // display the response
           console.log(response);
           $(container).empty();       
           $(container).html(response);
            modal.style.display = "block";
        });
    });
});
</script>
<?php
}
add_action( 'wp_footer', 'pop_up' );


add_action('wp_ajax_show_product', 'show_product_callback_wp');
add_action( 'wp_ajax_nopriv_show_product', 'show_product_callback_wp' );
function show_product_callback_wp() {
     $url = $_POST['url'];
     $product_id = url_to_postid( $url );

    // product content
    $content_post = get_post($product_id);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);

     $output = "";
     $output .= get_the_post_thumbnail( $product_id, 'medium');;
     $output .= $content;

     echo $output;
     exit(); 
}

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

1 Reply

0 votes
by (71.8m points)
等待大神答复

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

...