REMOVE_ACTION-PRE_GET_POST-不恢复原始查询

时间:2018-06-05 作者:Goran Džepina

我有以下功能。。。

function ajax_sortposts() {
    global $wp_query;
    $sorting_order = $_POST[\'sorting_order\'];

    if ( $sorting_order == \'Latest\' ) {
        remove_action( \'pre_get_posts\', \'query_get_posts_by_views\' );
        wp_reset_postdata();
    }
    else {
        add_action( \'pre_get_posts\', \'query_get_posts_by_views\' );
    }

    get_content();

    die;
} 

function get_content () {
    global $wp_query;
    wp(); 
?>
    <div id="post-wrapper" class="grid-wrapper">
        <?php
            if ( have_posts() ) :
                echo \'<div class="gallery-wrapper">\';
                while ( have_posts() ) : the_post();
                    if ( \'one-column\' === get_option( \'baseline_customizer_post_style\', \'one-column\' ) ) {
                        get_template_part( \'template-parts/content\' );
                    } else {
                        get_template_part( \'template-parts/content-grid-item\' );
                    }
                endwhile;

                echo \'</div>\';
            else :
                get_template_part( \'template-parts/content-none\' );
            endif;

            if (  $wp_query->max_num_pages > 1 )
                echo \'<div class="loadmore_posts">More posts</div>\';
        ?>
    </div>
<?php 
}

function query_get_posts_by_views( $query ) {

    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set(\'post_type\', \'post\');
        $query->set(\'posts_per_page\', get_option(\'posts_per_page\'));
        $query->set(\'paged\', 1);
        $query->set(\'post_status\', \'publish\');
        $query->set(\'ignore_sticky_posts\', true);
        $query->set(\'tag__not_in\', array(14)); 
        $query->set(\'order\', \'DESC\');
        $query->set(\'meta_key\', \'link_click_counter\');
        $query->set(\'orderby\', \'meta_value_num\');
        $query->set(\'date_query\', 
            [    [
                \'column\' => \'post_date_gmt\',
                \'after\'  => \'130 days ago\',
            ]    ] 
        );

        return ($query);
    }
}
单击“我想按帖子浏览次数更改主页上帖子的顺序”,或将顺序返回到默认值。除了remove\\u操作(“pre\\u get\\u posts”不会返回到原始查询(它复制了一些posts),其他操作都正常。我做错了什么?

Ajax功能:

    jQuery( document ).on( \'click\', \'[class*=sortingMenu]\', function() {
  var sorting_order = jQuery(this).attr(\'sorting_order\');
  jQuery.ajax({
    url : ajaxposts.ajax_posts_url,
    type : \'post\',
    data : {
        action : \'sortposts\',
        sorting_order : sorting_order
    },
    beforeSend:function( xhr ){
        document.getElementById("sortingLoader").style.visibility = "visible";


    },
    success : function( response ) {

        if (sorting_order == "Latest") {
            document.getElementById("Latest").classList.add(\'selectedSort\');
            document.getElementById("MostViewed").classList.remove(\'selectedSort\');
        }
        else {
            document.getElementById("MostViewed").classList.add(\'selectedSort\');
            document.getElementById("Latest").classList.remove(\'selectedSort\');
        }           

        jQuery(\'#post-wrapper\').remove();
        jQuery(\'.pagination\').remove();
        jQuery(\'#main\').append(response);
        loadmore_posts_params.current_page = 1;

        // Fade in the images as they load
        function fade_images() {
        $(\'.gallery-wrapper .gallery-thumb\').each(function(i) {
            var row = $(this);
            setTimeout(function() {
                row.addClass(\'fadeInUp\');
            }, 90*i)
        });
        }

        // Masonry blocks
        var $blocks = $(\'.two-column .gallery-wrapper,.three-column .gallery-wrapper\');

        $blocks.imagesLoaded( function() {
            $blocks.masonry({
            itemSelector: \'body:not(.one-column) .post\',
            transitionDuration: 0
        });

        // Fade blocks in after images are ready
        fade_images();
        });

        document.getElementById("sortingLoader").style.visibility = "hidden";
    },
    error: function () {
        document.getElementById("sortingLoader").style.visibility = "hidden";
    }     
});

return false;

})
以下是选项链接:

   function sorting_menu() { ?>

    href="javascript:void(0)" sorting_order="Latest" id="Latest" class="sortingMenu selectedSort">Latest</a>
    &ensp;
    href="javascript:void(0)" sorting_order="MostViewed" id="MostViewed" class="sortingMenu">Most viewed</a>


  } 

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

首先,AJAX请求是独立的,因此您不必remove_action 如果您之前没有添加它。。。

老实说,我真的不明白你的代码-你修改了全局wp_query 对象,但不太清楚在AJAX调用过程中如何以及为什么会创建任何查询-WP以不同的方式处理这些请求。。。说到这里,这里的代码应该可以工作。。。(它不需要对JS进行任何更改,所以我只发布PHP代码)

function ajax_sortposts() {
    $sorting_order = $_POST[\'sorting_order\'];

    // we don\'t use any global $wp_query, since no global $wp_query is created during AJAX calls
    // instead we create our own WP_Query instance - so we don\'t need to use pre_get_posts
    $posts_query = new WP_Query( array(
        \'post_type\' => \'post\',
        \'posts_per_page\', get_option(\'posts_per_page\'),
        \'paged\' => 1,
        \'post_status\' => \'publish\',
        \'ignore_sticky_posts\' => true,
        \'tag__not_in\' => array(14),
        \'order\' => \'DESC\',
        \'date_query\' => array(
            array(
                \'column\' => \'post_date_gmt\',
                \'after\'  => \'130 days ago\',
            )
        )
    ) );
    if ( \'MostViewed\' == $sorting_order ) {
        $posts_query[\'meta_key\'] = \'link_click_counter\';
        $posts_query[\'orderby\'] = \'meta_value_num\';
    }

    get_content( $posts_query );

    die;
} 

function get_content ( $query ) {
    // again we shouldn\'t use global $wp_query in here
    // and certainly we SHOULDN\'T call wp() function at all...
?>
    <div id="post-wrapper" class="grid-wrapper">
        <?php
            if ( $query->have_posts() ) :
                echo \'<div class="gallery-wrapper">\';
                while ( $query->have_posts() ) : $query->the_post();
                    if ( \'one-column\' === get_option( \'baseline_customizer_post_style\', \'one-column\' ) ) {
                        get_template_part( \'template-parts/content\' );
                    } else {
                        get_template_part( \'template-parts/content-grid-item\' );
                    }
                endwhile;

                echo \'</div>\';
            else :
                get_template_part( \'template-parts/content-none\' );
            endif;

            if (  $query->max_num_pages > 1 )
                echo \'<div class="loadmore_posts">More posts</div>\';
        ?>
    </div>
<?php 
}

结束