【问题标题】:Pagination within ajax fails to go to correct pageajax 中的分页无法转到正确的页面
【发布时间】:2019-12-21 07:04:03
【问题描述】:

我正在使用 ajax 基于过滤器加载帖子。如果超过 9 个,我就会使用分页功能。虽然分页调用了正确的页数,但链接本身不起作用。相反,他们会转到以站点 url + /wp-admin/admin-ajax.php?paged=2 结尾的页面。那一页是空白的,上面有一个 0。而已。

当我使用 javascript 将分页链接动态覆盖到正确的链接中时,页面只会进入相同的原始页面。

感谢任何帮助。

我的functions.php中的ajax代码

add_action( 'wp_ajax_myfilter', 'posts_filter_function' );
add_action( 'wp_ajax_nopriv_myfilter', 'posts_filter_function' );

function posts_filter_function() {

$args = array(
    'order'          => 'DESC',
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 9,
    'paged' => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1,
);

// for categories!
if( isset( $_POST['categoryfilter'] ) )
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field'    => 'id',
            'terms'    => $_POST['categoryfilter']
        )
    );

// for topics!
// if( isset( $_POST['topicfilter'] ) )
// $args['tax_query'] = array(
//  array(
//      'taxonomy' => 'topics',
//      'field' => 'id',
//      'terms' => $_POST['topicfilter']
//  )
// );

$query = new WP_Query( $args );
$backup_image = get_field( 'featured_image_global', 'option' );
?>
<div class="news-grid grid-x small-up-1 medium-up-3">
    <?php
    if ( $query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            $image = get_the_post_thumbnail_url( $post->ID, 'featured-large' );
            if ( $image ) {
                $image = get_the_post_thumbnail_url( $post->ID, 'featured-large' );
            } else {
                $image = $backup_image;
            }
            ?>
            <div class="cell posts__filter--item">
                <a href="<?php echo esc_html( get_post_permalink( $post->ID ) ); ?>">
                    <div class="card">
                        <div class="card-section">
                        <img
                        src="<?php echo esc_attr( $image ); ?>"
                        alt="<?php echo esc_html( get_post_meta( get_post_thumbnail_id( $post->ID ), '_wp_attachment_image_alt', true ) ); ?>">

                            <p class='date'><?php echo esc_html( get_the_date( 'd M \'y', $post->ID ) ); ?></p>
                            <h4><?php echo esc_html( get_the_title( $post->ID ) ); ?></h4>
                            <p class='author'><?php echo esc_html( post_authors( $post ) ); ?></p>
                        </div>
                    </div>
                </a>
            </div>
            <?php
        endwhile;
        ?>
    </div>
            <div class="pagination--container">
        <?php
        echo paginate_links(
            array(
                'base'      => get_home_url() . '/news/' . '%_%',
                'format'    => '?paged=%#%',
                'current'   => max( 1, get_query_var( 'paged' ) ),
                'total'     => $query->max_num_pages,
                'prev_text' => '1',
                'next_text' => '1',
            )
        );
        ?>
    </div>
        <?php
        wp_reset_postdata();
    else :
        echo '<h2 class="no-posts">No posts found</h2>';
    endif;
    die();
}

我的filter.php中的过滤器表单

$categories = get_terms(
array(
    'taxonomy'   => 'category',
    'hide_empty' => true,
    'orderby'    => 'name',
)
);

$topics = get_terms(
array(
    'taxonomy'   => 'topics',
    'hide_empty' => true,
    'orderby'    => 'name',
)
);
?>

<form
action="<?php echo site_url() ?>/wp-admin/admin-ajax.php"
method="POST"
class="searchandfilter"
id="filter">

<section class='postfilter'>
    <div class="postfilter--filters flex-container flex-dir-column large-flex-dir-row">

        <div class="flex-child-auto">
            <input type="hidden">
            <p class="">Filter By:</p>
        </div>

        <div class="ui-group flex-child-auto">
            <select class="select--topic postform" name="topicfilter">
                <option value="All">Topic</option>
                <?php
                foreach ( $topics as $topic ) {
                    ?>
                <option value="<?php echo esc_html( $topic->term_id ); ?>"><?php echo esc_html( $topic->name ); ?></option>
                    <?php
                }
                ?>
            </select>
        </div>

        <div class="ui-group flex-child-auto">
            <select class="select--category postform" name="categoryfilter">
                <option value="All">Category</option>
                <?php
                foreach ( $categories as $category ) {
                    ?>
                <option value="<?php echo esc_html( $category->term_id ); ?>"><?php echo esc_html( $category->name ); ?></option>
                    <?php
                }
                ?>
            </select>
        </div>

        <div class="flex-child-auto ui-group">
            <button class="button button--orange button--filter">
                Submit
            </button>
            <input type="hidden" name="action" value="myfilter">
        </div>
    </div>
</section>

jquery 代码

 $('#filter').submit(function(){
  var filter = $('#filter');
  var text = $('.no-posts');
  var currentPosts = $('#response');
  $.ajax({
    url:filter.attr('action'),
    data:filter.serialize(), // form data
    type:filter.attr('method'), // POST
    beforeSend:function(xhr){
      text.text('Loading Posts...');
      text[0].style.margin = '10rem auto';
      currentPosts[0].style.display = 'none';
    },
    success:function(data){
      text.text('');
      text[0].style.margin = 0;
      currentPosts[0].style.display = 'block';
      $('#response').html(data); // insert data
    }
  });
  return false;
});

【问题讨论】:

  • 您是否尝试过更改paginate_links 函数中的'base' 属性?
  • 嘿,埃米尔。是的,我有。我试过'base' =&gt; get_pagenum_link(1) . '%_%',
  • 好吧,我遇到过几次你的情况,并且做了同样的事情,就是用 JS 手动更改链接。但现在我看它,我认为'base' 属性是罪魁祸首。尝试使用附加'%_%' 的分页页面的 url 对基本属性进行硬编码,以了解我的意思。
  • 感谢您的关注。我试着做你刚才提到的事情,这给了我经典的404 page not found

标签: javascript php jquery ajax wordpress


【解决方案1】:

问题在于'base' 属性,它将从正在呈现它的页面引用。如果您使用str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),如WordPress文档中所述,它将从当前页面创建一个URL,在admin-ajax.php文件中将变为/wp-admin/admin-ajax.php

所以我们需要使base 属性动态化。

动态输入字段

在您的表单中添加另一个隐藏的输入元素,该元素引用您所在的页面。这样我们就不必更改 JS,并且可以根据需要在 HTML 中添加或删除输入字段。

<?php
global $wp;
$base = home_url( $wp->request ); // Gets the current page we are on.
?>

<input type="hidden" name="base" value="<?php echo $base; ?>"/>

此输入可以将 URL 发送到 AJAX 函数并将其用作paginate_links 函数的base 属性。

检查posts_filter_function 函数中的base 值。

// Fallback if there is not base set.
$fallback_base = str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) );

// Set the base.
$base = isset( $_POST[ 'base' ] ) ? trailingslashit( $_POST[ 'base' ] ) . '%_%' : $fallback_base;

然后将基值作为paginate_links 函数的参数传递。

paginate_links(
    array(
        'base'      => $base,
        'format'    => '?paged=%#%',
        'current'   => max( 1, get_query_var( 'paged' ) ),
        'total'     => $query->max_num_pages,
        'prev_text' => '1',
        'next_text' => '1',
    )
);

所以输入字段的值将决定base 属性将变成什么。

Alternative:也可以在 jQuery Ajax 请求中简单地添加当前 URL。在data属性中传递序列化数据之前添加:

'&base=' + location.hostname + location.pathname;

这与输入解决方案相比不太可取,因为它需要某种硬编码,但当 HTML 无法操作时可能是一种选择。

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多