简体   繁体   中英

Wordpress loadmore button does not work. $wp_query not returning last post loop query

-- Edit 1 --

Found out some new things. I'm adding them on top since they might be more relevant than the code below.

I've rerun the scripts a few times. I now get different findings actually. Running var_dump($wp_query->query); right after $the_query = new WP_Query($queryArgs); In the first render of the post loop gives me the query vars of the page the loop is rendered on. Calling it with ajax it reruns the same part of the code, right? So than it returns empty.

My thoughts:

  • Pages is called, runs funtions.php.
  • Runs the part of the wp_enqueue_script('rtt_scripts');
  • This is the moment it gets the current $wp_query values. Which are the values of the page.
  • Than renders the page with the post loop.
  • This is the moment the post loop runs $the_query = new WP_Query($queryArgs);
  • On press of the load more the ajax than calls it to rerun the post loop. With the query vars set with wp_enqueue_script('rtt_scripts');

This made me think. Am I running the code in a wrong order? Are the query vars for ajax set on the wrong moment? Other thought. Should I focus on how to get the query vars on the first post loop to the ajax query vars?

-- End Edit --

I'm having trouble with a load more button in Wordpress. The code below is the basic code I have right now. As far as I can see this should be a working code :) Problem is though that this doesn't work.

My problem is that I don't know where to start debugging. Closest I know where the problem lies is this:

In rtt_loadmore_ajax_handler() there is the var $queryArg When var_dumping the var $queryArg in both rtt_post_grid() and rtt_loadmore_ajax_handler()

It gives different results. Here I would expect the same results. In the Ajax call it returns the arguments of the current rendered page and not of the post query on this page.

Would the global $wp_query; be the problem? And how do I go from here?

The basic post code:

function rtt_post_grid()
{

    $queryArgs = Array(
        "post_type" => Array(
            'news',
            'agenda'
        ),
        'posts_per_page' => 4,
        'post_status' => 'publish',
        'paged' => 1
    );

    // post grid wrap
    echo '<div id="rtt_posts_wrap"  >';

        rtt_post_grid_query($queryArgs);

    echo '</div>';

    // load more button
    echo '<form>';
        echo '<button id="rtt_loadmore" class=" button">Load more post</button>  ';
        echo '<input type="hidden" name="action" value="loadmore" />'; // this line might be obsolete
    echo '</form>';
}

function rtt_post_grid_query($queryArgs)
{

    // The Query
    $the_query = new WP_Query($queryArgs);
    // The Loop
    if ($the_query->have_posts()) {
        echo '<ul>';
        while ($the_query->have_posts()) {
            $the_query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
        echo '</ul>';
        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
        // no posts found
        echo 'no posts found';
    }
}

Setting the JS:

if(!has_action('rtt_post_grid_script_and_styles')) {
    add_action('wp_enqueue_scripts', 'rtt_post_grid_script_and_styles', 1);

    function rtt_post_grid_script_and_styles()
    {
        global $wp_query;

        wp_register_script('rtt_scripts', plugin_dir_url( __FILE__ ) . 'js/script.js', array('jquery'), time());
        wp_enqueue_script('rtt_scripts');

        wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
            'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
            'posts' => json_encode($wp_query->query_vars), // everything about your loop is here
            'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
            'max_page' => $wp_query->max_num_pages
        ));

        wp_enqueue_script('rtt_scripts');
    }
}

The JS/Ajax:

jQuery(function($){

    $(window).ready(function() {

        $('#rtt_loadmore').click(function () {

            $.ajax({
                url: rtt_loadmore_params.ajaxurl,
                data: {
                    'action': 'loadmore', // the parameter for admin-ajax.php
                    'query': rtt_loadmore_params.posts, // loop parameters passed by wp_localize_script()
                    'page': rtt_loadmore_params.current_page, // current page
                },
                dataType: 'json',
                type: 'POST',

                beforeSend: function (xhr) {

                    $('#rtt_loadmore').text('Bezig met laden...'); // some type of preloader
                },
                success: function (data) {

                    if (data) {

                        $('#rtt_loadmore').text('More posts');

                        $('#rtt_posts_wrap').append(data.content); // insert new posts

                        rtt_loadmore_params.current_page++;

                        if (rtt_loadmore_params.current_page == rtt_loadmore_params.max_page){

                            $('#rtt_loadmore').hide(); // if last page, HIDE the button

                        }
                    } else {

                        $('#rtt_loadmore').hide(); // if no data, HIDE the button as well
                    }
                }
            });

            return false;
        });
    });
});

The Ajax handler:

add_action('wp_ajax_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'rtt_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

function rtt_loadmore_ajax_handler(){

    $postData = $_POST;

    // prepare our arguments for the query
    $queryArgs = json_decode( stripslashes( $postData['query'] ), true );
    $queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
    $queryArgs['post_status'] = 'publish';

    ob_start();

    rtt_post_grid_query($queryArgs);

    $output = ob_get_contents();

    ob_end_clean();

    global $the_query;

    echo json_encode( array(
        'posts' => serialize( $the_query->query_vars ),
        'max_page' => $the_query->max_num_pages,
        'found_posts' => $the_query->found_posts,
        'content' => $output
    ) );

    die;
}

Add the two order arguments to $queryArgs.

// prepare our arguments for the query
$queryArgs = json_decode( stripslashes( $postData['query'] ), true );
$queryArgs['paged'] = $postData['page'] + 1; // we need next page to be loaded
$queryArgs['post_status'] = 'publish';

$queryArgs['orderby'] = 'date'; // add this to order by date
$queryArgs['order'] = 'DESC'; // add this to display the most recent

So, I've figured it out. I'll explain for it might be useful to somebody else.

The reason it did not work is because the code above is more useful in a template. But I use it in a shortcode. The wp_localize_script() was run on rendering the page and not on running the shortcode. That's why it didn't had the right variables.

I've moved the code below inside the shortcode. Right after the new WP_query:

// The Query
$the_query = new WP_Query($queryArgs);

// The Loop
if ($the_query->have_posts()) {

    wp_enqueue_script_ajax_vars($the_query);

Than passed the new query

function wp_enqueue_script_ajax_vars($the_query)
{
wp_register_script('rtt_scripts', plugin_dir_url(__FILE__) . 'js/script.js', array('jquery'), time());

wp_localize_script('rtt_scripts', 'rtt_loadmore_params', array(
    'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
    'posts' => json_encode($the_query->query_vars), // everything about your loop is here
    'query_vars' => json_encode($the_query->query),
    'current_page' => $the_query->query_vars['paged'] ? $the_query->query_vars['paged'] : 1,
    'max_page' => $the_query->max_num_pages,
));

wp_enqueue_script('rtt_scripts', '', '', '', true); // note the last 'true' this sets it inside the footer
}

Resulting in wp_localize_script() creating the variable in the footer. It was in the header before. But by getting it within the shortcode, sending the new query arguments and putting them inside the footer (since the header is already rendered by then) I have set the JS var for Ajax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM