Pavel Němec
Pavel Němec

Reputation: 272

woocommerce: show recent products throught Ajax

Do you anybody knows some easy way how to show Woocommerce recent products throught ajax (use some callback or something like this)? Now I have this shortcode:

[recent_products per_page="12" columns="3"]

I want to create a button which would me allow to show next 12 products on same page.

Upvotes: 0

Views: 1098

Answers (1)

Danijel
Danijel

Reputation: 12689

A quick example, it is basic wordpress ajax call that returns the output of recent_products shortcode. Put a link with #wc_recent_products id somewhere on page, the ajax response will replace the content of div#main ( $( '#main' ).html( response );, change that line if you want to put the content somewhere else ).

<?php

add_action( 'wp_ajax_wc_recent_products', function() 
{
    if ( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'wc_recent_products' ) ) 
    {
        echo do_shortcode( '[recent_products per_page="12" columns="3"]' );
    }
    exit();
});


add_action( 'wp_head', function() {

?>
    <script type="text/javascript" >
    jQuery(function ($) {
        $( '#wc_recent_products' ).on( 'click', function() {
            $.post( 
                '<?php echo admin_url( 'admin-ajax.php' ); ?>', 
                { action: 'wc_recent_products', nonce: '<?php echo wp_create_nonce( 'wc_recent_products' ); ?>' }, 
                function( response ) {              
                    $( '#main' ).html( response );          
                }
            );
            return false;
        });
    });
    </script>
<?php
});
?>

Upvotes: 5

Related Questions