简体   繁体   English

WordPress的loadmore按钮不起作用。 $ wp_query不返回上一次循环查询

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

-- Edit 1 -- -编辑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); 运行var_dump($wp_query->query); right after $the_query = new WP_Query($queryArgs); $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. 在post循环的第一个渲染中,为我提供了循环渲染页面的查询变量。 Calling it with ajax it reruns the same part of the code, right? 用ajax调用它会重新运行代码的相同部分,对吗? So than it returns empty. 所以比它返回空。

My thoughts: 我的想法:

  • Pages is called, runs funtions.php. 页面被调用,运行funtions.php。
  • Runs the part of the wp_enqueue_script('rtt_scripts'); 运行wp_enqueue_script('rtt_scripts');的一部分wp_enqueue_script('rtt_scripts');
  • This is the moment it gets the current $wp_query values. 这是它获取当前$wp_query值的时刻。 Which are the values of the page. 页面的值。
  • Than renders the page with the post loop. 比用post循环渲染页面。
  • This is the moment the post loop runs $the_query = new WP_Query($queryArgs); 这是post循环运行$the_query = new WP_Query($queryArgs);
  • On press of the load more the ajax than calls it to rerun the post loop. 按下负载后,ajax会比调用它来重新运行post循环更多。 With the query vars set with wp_enqueue_script('rtt_scripts'); 使用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? Ajax的查询变量是否在错误的时刻设置? Other thought. 其他想法。 Should I focus on how to get the query vars on the first post loop to the ajax query vars? 我应该专注于如何在ajax查询变量的第一个发布循环中获取查询变量吗?

-- End Edit -- -结束编辑-

I'm having trouble with a load more button in Wordpress. 我在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() rtt_loadmore_ajax_handler()还有就是VAR $queryArg当var_dumping了var $queryArg两个rtt_post_grid()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. 在Ajax调用中,它返回当前渲染页面的参数,而不返回该页面上的后查询的参数。

Would the global $wp_query; 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: 设置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: 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: Ajax处理程序:

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. 将两个顺序参数添加到$ 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. wp_localize_script()在呈现页面时运行,而不是在运行简码时运行。 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: 在新的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. 结果是wp_localize_script()在页脚中创建了变量。 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. 但是通过在短代码中获取它,发送新的查询参数并将其放在页脚中(因为此时标题已被渲染),我为Ajax设置了JS var。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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