How to show more posts when you click button?

Asked

Viewed 2,077 times

1

In the loop I put to show 12 Woocommerce products.

<div id="vitrine" class="container-fluid">
        <?php
            $args = array(
                'post_type' => 'product',
                'posts_per_page' => 12
                );
            $loop = new WP_Query( $args ); ?>           

            <div class="row">
                <div class="col-md-offset-1 col-md-10">
                <?php if ( $loop->have_posts() ) {
                while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <div class="col-md-3 prod">
                        <div class="interna">
                            <div class="faixa"></div>
                            <?php woocommerce_get_template_part( 'content', 'product' );?>
                        </div>
                    </div>
                <?php endwhile;
            } else {
                echo __( 'No products found' );
            }
            wp_reset_postdata();
        ?>
    </div>

Behold: http://kisadesign.com.br/paulalima/

I would like to put a button (+ SEE MORE PRODUCTS) and each time someone clicks on it 4 more products appear.

Does anyone have any suggestions on how to do this?

1 answer

2


Your button (+ SEE MORE PRODUCTS) must call an AJAX function to load 4 more products from the database.

To use paging with AJAX you need:

  1. Queue a script in Wordpress that will call the AJAX function and AJAX itself
  2. Load post offset in script (to skip products that have already appeared)
  3. Add the function that will be called by AJAX

So to get started on the functions.php of your theme:

add_action( 'wp_enqueue_scripts', 'meus_scripts', 100 );

function meus_scripts() {
wp_enqueue_script(
    'meus_scripts',
    get_template_directory_uri() . '/js/scripts.js?ver=1.0', //esse é o arquivo .js do seu tema que vai conter todos os scripts (pode ser diferente no seu tema)
    array( 'jquery' ),
    null,
    false
);
wp_localize_script(
    'meus_scripts',
    'WPaAjax',
    array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    )
);
}

In the scripts.js of your theme you add the code that will call AJAX, and add a variable offset, counting the products that have already been loaded, which will be called later by Wp_query.

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

$('#maisprodutos').click(function(e){  
    e.preventDefault(); 
    var offset = $('.col-md-offset-1 col-md-10').length; //o ideal é dar uma id para essa div
    $.post(
        WPaAjax.ajaxurl,
        {
            action : 'mais_produtos',
            offset : offset
        },
        function( response ) {
            $('.faixa').append( response );
        }
    );
});

});

Now all you need to do is add the function that will process the AJAX call according to javascript. For this you need to use the action wp_ajax

add_action('wp_ajax_mais_produtos', 'mais_produtos');
add_action('wp_ajax_nopriv_mais_produtos', 'mais_produtos');

function mais_produtos(){
global $wp_query;

$offset = $_POST['offset'];
$args = array(
    'offset' => $offset,
    'posts_per_page' => 4
);
$wp_query = new WP_Query( $args );

woocommerce_get_template_part( 'content', 'product' );

exit;
}

Your code will look like this:

<div id="vitrine" class="container-fluid">
    <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12, //Quantos produtos aparecerão na página inicial?
            );
        $loop = new WP_Query( $args ); ?>           

        <div class="row">
            <div class="col-md-offset-1 col-md-10">
            <?php if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post(); ?>
                <div class="col-md-3 prod">
                    <div class="interna">
                        <div class="faixa"></div>
                        <?php woocommerce_get_template_part( 'content', 'product' );?>
                    </div>
                </div>
            <?php endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
</div>
<div id="mais-prod">
    <p><a href="#" id="mais_produtos">+ VEJA MAIS PRODUTOS</a></p>
    <div class="divisoria"></div>

</div>

This code is just one example. Ideally, functions have unique names and your Ids have ids. Although most of the functions of plugins and Wordpress themes are in English, the best practice is to add the name of your theme/plugin before the function name.

I hope it helps!

  • I was able to implement according to your suggestion, but I’m having difficulty increasing the offset. The way it is when I click the button (+ SEE MORE PRODUCTS) always the same products appear. Would you have any suggestion?

  • The way the js is counting the number of Divs and returning the offset var offset = $('.col-md-offset-1 col-md-10').length; //o ideal é dar uma id para essa div. Have you created an id for the div? After this line put an Alert(offset) to see if it is reading the amount of Divs correctly...

  • I put an id for the div, but I’m assigning the value like this = If (first time) { var offset = 12} If not {var offset = 4}. The problem now is to define how to identify which is the first time. Have any suggestions?

  • Sorry, but I didn’t see your question before... by the time I think it should have solved, but if anyone else comes up with the same question, the offset should take the amount of products that appear and add in the offset. For example if there are 12 products appearing, it will offset 12 and pick up 4 products. When calling again will be 16 products and that is the offset value. The offset determines how many posts will be "skipped" . If you want to change the quantity of products searched for, you have to change the posts_per_page and not the offset...

  • @Ricardobrgweb Hello, would it be possible to apply the solution to use multiple custom Query with ajax paging? I would like to have 3 Box on the same page, each box with a different category. So here: https://cloud.githubusercontent.com/assets/22301766/24335166/96282abe-124e-11e7-8485-94613e88de00.png

  • 1

    @Johnquimera Yes, it is possible... just add a variable with the category to the ajax request and treat the result in JS. But today, if I had to answer that question again, it would indicate using the REST API...

  • @Ricardobrgweb I understand. I have a code that I removed from another theme, and applied to my own. Which works in index, categories and so on. I noticed that it’s a little different, the loading apparently is done based on div, I don’t know. Could you not implement a reuse for several boxes with it? Maybe using a class to do an ID attr. https://pastebin.com/Xr9wTB32

  • @Ricardobrgweb asked a question, if you can give a hand. https://answall.com/q/302785/95735

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.