Woocommerce 商店页面分页 + AJAX WP_Query

问题描述 投票:0回答:0

我有一个商店页面的自定义分页。我还有一个用于此分页的 AJAX 处理程序。但问题是移动到下一页时,$current_page 和 pagination 没有更新。在 AJAX 处理程序中,我调用了分页函数,但它没有更新。如何解决?

我的分页:

function pagination()
{
    global $wp_query;

    // Get the total number of products
    $total_products = $wp_query->found_posts;

    // Determine current page and number of pages
    $current_page = max(1, get_query_var('paged'));
    $per_page = apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page());
    $num_pages = ceil($total_products / $per_page);

    // Define inactive class for arrows
    $inactive_class = 'pagination__arrow--inactive';

    // Start building the HTML for the pagination
    $pagination_html = '<div class="pagination__arrows">';

    if ($current_page > 1) {
        // Add HTML for previous arrow with link
        $pagination_html .= '<a href="#" class="pagination__arrow" data-page="' . ($current_page - 1) . '"></a>';
    } else {
        // Add HTML for inactive previous arrow
        $pagination_html .= '<span class="pagination__arrow ' . $inactive_class . '"></span>';
    }

    // Add HTML for page count
    $pagination_html .= '<p>' . sprintf(__('%d of %d', 'rl-woocommerce'), $current_page, $num_pages) . '</p>';

    if ($current_page < $num_pages) {
        // Add HTML for next arrow with link
        $pagination_html .= '<a href="#" class="pagination__arrow forward" data-page="' . ($current_page + 1) . '"></a>';
    } else {
        // Add HTML for inactive next arrow
        $pagination_html .= '<span class="pagination__arrow forward ' . $inactive_class . '"></span>';
    }

    // Close the HTML for the pagination
    $pagination_html .= '</div>';

    return $pagination_html;
}

AJAX 处理程序:

function load_products()
{

    // Get the current page from the AJAX request
    $paged = $_POST['page'] ? $_POST['page'] : 1;

    // Set up the query for the requested page
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => apply_filters('loop_shop_per_page', wc_get_default_products_per_row() * wc_get_default_product_rows_per_page()),
        'paged'          => $paged,
    );
    $products = new WP_Query($args);

    // Start building the HTML for the product list
    ob_start();
    woocommerce_product_loop_start();
    while ($products->have_posts()) {
        $products->the_post();
        wc_get_template_part('content', 'product');
    }
    woocommerce_product_loop_end();
    wp_reset_postdata();
    $product_html = ob_get_clean();

    rl_woocommerce_pagination();

    // Return the data in JSON format
    $data = array(
        'product_html'    => $product_html,
    );
    wp_send_json_success($data);
}

php ajax wordpress woocommerce
© www.soinside.com 2019 - 2024. All rights reserved.