Ajax 过滤器在首次加载时不会根据 url 参数进行更新

问题描述 投票:0回答:1
add_action( 'wp_ajax_nopriv_filter', 'team_filter_ajax' );
add_action( 'wp_ajax_filter', 'team_filter_ajax' );

function team_filter_ajax() {
    $category = isset( $_POST['category'] ) ? sanitize_text_field( $_POST['category'] ) : 'all';
    $search_term = sanitize_text_field( $_POST['search_term'] );
    print_r($category);

    $args = array(
        'post_type' => 'member',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'menu_order',
    );

    // Create an empty tax_query array
    $tax_query = array(
        'relation' => 'AND',
    );

    if ( $category !== 'all' ) {
        $tax_query[] = array(
            'taxonomy' => 'members_category',
            'field' => 'slug',
            'terms' => $category,
        );
    }

    if ( $search_term ) {
        $args = array(
            'post_type' => 'member', // Adjust this to your post type
            'posts_per_page' => -1,
            's' => $search_term,
        );
    }

    // Add the tax_query to the main $args
    if ( ! empty( $tax_query ) ) {
        $args['tax_query'] = $tax_query;
    }

    $query = new WP_Query( $args );
    $response = '';

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $response .= render_template( 'template-parts/parts/member-item.php' );
        }
    } else {
        // No members found
        $response = 'No members found.';
    }

    wp_reset_postdata();
    echo $response;
    die();
}

我需要根据 url 中发送的参数使此过滤器工作,例如:mydomain/pagename/?cat=category-name,但类别始终为“all”,这意味着

$_POST['category']
在我的第一页加载。从下拉列表中选择后,此变量
$category
将根据参数名称进行更改。因此,过滤器始终在首页加载时显示所有团队成员。除此之外,一切正常,文件管理器按预期工作:

这是我的jquery代码

var $ = require('jquery');

require('webpack-jquery-ui/selectmenu');


$(function() {
    initAjaxParameters();
    initCategorySelect();
    filterTeam();
    ajaxFilter();
});


$.urlParam = function(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null){
        return null;
    }
    else {
        return decodeURI(results[1]) || 0;
    }
};


let parameters = {};
let postsXhr = null;


function filterTeam() {

    // Initialize the selectmenu widget
    $('#category').selectmenu({
        change: function (event, ui) {
            var category = ui.item.element.data('category'); // Get the data-category attribute
            var searchTerm = $('#search-member').val(); // Get the search term
            

            let url = '';

            if (category) {
                url = url + '?cat=' + category;
            }
            ajaxFilter(category, searchTerm);
            window.history.pushState('next', document.title, url);
        }
    });
    

    // Add an event listener for the search input field
    $('#search-member').on('input', function () {
        var searchTerm = $(this).val();
        var category = $('.filter-wrap > select').find('option:selected').attr('data-category');
        ajaxFilter(category, searchTerm);
    });
}
function initAjaxParameters() {
    parameters.action = 'team_filter_ajax';
    parameters.category = $.urlParam('cat'); // Set the initial category from URL

    // Set the selected option in the select menu

    $('#category').val(parameters.category);

    if (parameters.category) {
        $('#category .ui-menu-item').filter(function () {
            console.log('here');
            return $(this).data("category") == parameters.category;
        }).click(); // Use .click() to trigger the click event
    }
}



function initCategorySelect() {
    $('#category').selectmenu({
        change : function(){
            parameters.category = $(this).val();
            ajaxFilter();
         
        }
    });
}

function pushHistory() {
    let url = window.location.href.split('?')[0];

    if(parameters.category){
        url = url + '?cat=' + parameters.category;
    }

    window.history.pushState('next', document.title, url);
}


function ajaxFilter(category, searchTerm) {
    pushHistory();
    $('.ajax-loader').removeClass('opacity-0');
    if(postsXhr){
        postsXhr.abort();
    }

 
    $.ajax({
        url: ajax_params.ajaxurl,
        data: { action: 'filter', category: category, search_term: searchTerm },
        type: 'post',
    
        success: function (result) {
            $('.team-section__wrap .inner').html(result);
            $('.ajax-loader').addClass('opacity-0');
        },
        error : function(){
            console.log('Something went wrong!');
        }
    });
}
php jquery ajax wordpress filter
1个回答
0
投票

team_filter_ajax 函数存在问题,您还需要修改 team_filter_ajax 过滤器以检查 GET 参数。像这样

$category = isset($_POST['category']) ? sanitize_text_field($_POST['category']) : (isset($_GET['cat']) ? sanitize_text_field($_GET['cat']) : 'all');

并且稍微需要修改服务器端响应的 js 代码:

$(function() {
    initAjaxParameters();
    initCategorySelect();
    filterTeam();

    let initialCategory = $.urlParam('cat');
    if(initialCategory) {
        ajaxFilter(initialCategory, '');
    } else {
        ajaxFilter('all', '');
    }

});
© www.soinside.com 2019 - 2024. All rights reserved.