最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How can I with implement ajax based numbered pagination to posts which are displayed via ajax? - Stack Overflow

programmeradmin3浏览0评论

What I'm trying to accomplish is producing numbered pagination for posts which are loaded via an ajax function. I have to make the numbered pagination work via ajax as well. Explanation of each code block below:

This function produces taxonomy terms which currently have posts assigned. Code resides in functions.php.

<?php
    function ee_event_categories() {
      $event_cats = get_terms( array(
        'taxonomy' => 'tribe_events_cat',
        'hide_empty' => true,
      ) );
    ?>
        <div class="filter-column category-block">
          <?php foreach ( $event_cats as $event_cat ) : ?>
            <button 
              data-taxonomy="<?php echo $event_cat->taxonomy; ?>" 
              data-slug="<?php echo $event_cat->slug; ?>"
              data-term-id="<?php echo $event_cat->term_id; ?>">
              <?php echo $event_cat->name; ?>
            </button>
          <?php endforeach; ?>
        </div>
    <?php
      $cat = ob_get_clean();
      return $cat;
    }
    add_shortcode( 'ee_event_categories', 'ee_event_categories' );
?>

Upon clicking on the resulting buttons from the previous function, a custom WP_Query runs and displays posts that match the criteria in the function below. This function resides in functions.php. I think I have to pass the $paged variable from the load_events_by_category() function into the javascript code. Unfortunately, I'm at a loss as to how to do it. Maybe the $paged variable needs to be applied as a second key / value pair in the wp_localize_script() declaration? Now I'm thinking out loud.

<?php
function load_events_by_category() {
  $paged = ($_POST['paged']) ? $_POST['paged'] : 1;
  $taxonomy = $_POST['taxonomy'];
  $slug = $_POST['slug'];
  $term_id = intval($_POST['term_id']);
    $category_events_args = array(
      'post_type'       => 'tribe_events',
      'posts_per_page'  => 4,
      'post_status'     => 'publish',
      'eventDisplay'    => 'custom',
      'order'           => 'ASC',
      'paged'           => $paged,
      'tax_query' => array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field'    => 'term_id',
          'terms'    => $term_id
        )
      )
    );
    $catquery = new WP_Query( $category_events_args );
    ob_start(); 
    if( $catquery->have_posts() ) : ?>
      <div class="this-weeks-events">
        <div class="featured-events-grid">
          <?php while ( $catquery->have_posts() ) : $catquery->the_post(); ?>
            <div class="featured-events-grid-child">
              <div class="event-date"
                data-taxonomy="<?php echo $taxonomy ?>"
                data-slug="<?php echo $slug; ?>" 
                data-term-id="<?php echo $term_id; ?>" 
                style="background:<?php echo the_field('event_category_background', $taxonomy . '_' . $term_id ); ?>"
              >
                <p class="event-day"><?php echo tribe_get_start_date( $event_id, false, 'D' ); ?></p>
                <p class="event-start-date" style="color:<?php echo the_field('event_date_color', $taxonomy . '_' . $term_id ); ?>"><?php echo tribe_get_start_date( $event_id, false, 'j' ); ?></p>
                <p class="event-month"><?php echo tribe_get_start_date( $event_id, false, 'F' ); ?></p>
              </div><!-- end div event-date -->

              <?php if( has_post_thumbnail() ) : ?>
                <div class="featured-image">
                  <a href="<?php echo the_permalink(); ?>"><?php the_post_thumbnail( 'full' ); ?></a>
                </div><!-- end div featured-image -->
              <?php endif; ?>
              <div class="featured-events-details-grid">
                <div><h2><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h2></div>
                <div>
                  <i class="far fa-clock" aria-hidden="true"></i>
                  <?php echo tribe_get_start_time( $event_id ); ?>
                  -
                  <?php echo tribe_get_end_time( $event_id ); ?>
                  <?php if( tribe_is_recurring_event() ) : ?>
                    <p class="event-recurring"><img src="<?php echo get_stylesheet_directory_uri() . '/images/arrows-rotate.webp' ?>" alt="rotating arrow icon for weekly events" width="20" height="20" /> Weekly Event</p>
                  <?php endif; ?>
                </div>
              </div><!-- end div featured-events-details-grid -->
            </div><!-- end div featured-events-grid-child -->
          <?php endwhile; ?>
        </div><!--end featured events grid -->        
        <?php
          $nextpage = $paged+1;
          $previouspage = $paged-1;
          $total = $catquery->max_num_pages;
          $pagination_args = array(
            'base'                => '%_%',
            'format'              => '?paged=%#%',
            'total'               => $total,
            'current'             => $paged,
            'show_all'            => false,
            'end_size'            => 1,
            'mid_size'            => 2,
            'prev_next'           => true,
            'prev_text'           => __('<span class="prev" data-attr="'.$previouspage.'">&laquo;</span>'),
            'next_text'           => __('<span class="next" data-attr="'.$nextpage.'">&raquo;</span>'),
            'type'                => 'plain',
            'add_args'            => false,
            'add_fragment'        => '',
            'before_page_number'  => '',
            'after_page_number'   => ''
          );
          $paginate_links = paginate_links($pagination_args);

          if ($paginate_links) : ?>
            <div id='pagination' class='pagination'>
              <?php echo $paginate_links; ?>
            </div>
          <?php endif; ?>
      </div><!-- end div this weeks events -->
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
    <?php
      $content = ob_get_clean();
      echo $content;
      die();
}
add_action( 'wp_ajax_load_events_by_category', 'load_events_by_category' );
add_action( 'wp_ajax_nopriv_load_events_by_category', 'load_events_by_category' );
?>

I'm not sure if this is important but I'll include it anyway. It's how I'm using wp_localize_script, also located in functions.php.

<?php wp_enqueue_script( 'ajax-load-category-events', get_stylesheet_directory_uri() . '/dist/ajax-category-events.js', array( 'jquery' ), '1.0', true ); 
wp_localize_script( 'ajax-load-category-events', 'categoryevents', array(
  'ajaxurl'   => admin_url( 'admin-ajax.php' )
));
?>

And finally, here's the code in above javascript file.

(function ($) {
  $(".category-block button").on('click', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: categoryevents.ajaxurl,
      data: {
        action: 'load_events_by_category',
        taxonomy: $(this).data('taxonomy'),
        slug: $(this).data('slug'),
        term_id: $(this).data('term-id')
      },
      success: function (html) {
        $('#fl-main-content').find('#event_results .fl-rich-text').empty();
        $('#event_results .fl-rich-text').append(html);
      },
      error: function (error) {
        console.log("Error: ", error)
      }
    })
  });
})(jQuery);

I actually did try passing the $paged variable into the script vars of the wp_localize_script declaration. I thought that would at least make the javascript "aware" of what page of results were showing.

wp_localize_script( 'ajax-load-category-events', 'categoryevents', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'paged' => $_POST['paged'] ? $_POST['paged'] : 1; ));

I also spent hours upon hours reviewing similar SO questions and looking for tutorials on how to solve this problem. I'll be darned but it doesn't seem using ajax pagination inside ajax produced content is much of a thing.

What I'm trying to accomplish is producing numbered pagination for posts which are loaded via an ajax function. I have to make the numbered pagination work via ajax as well. Explanation of each code block below:

This function produces taxonomy terms which currently have posts assigned. Code resides in functions.php.

<?php
    function ee_event_categories() {
      $event_cats = get_terms( array(
        'taxonomy' => 'tribe_events_cat',
        'hide_empty' => true,
      ) );
    ?>
        <div class="filter-column category-block">
          <?php foreach ( $event_cats as $event_cat ) : ?>
            <button 
              data-taxonomy="<?php echo $event_cat->taxonomy; ?>" 
              data-slug="<?php echo $event_cat->slug; ?>"
              data-term-id="<?php echo $event_cat->term_id; ?>">
              <?php echo $event_cat->name; ?>
            </button>
          <?php endforeach; ?>
        </div>
    <?php
      $cat = ob_get_clean();
      return $cat;
    }
    add_shortcode( 'ee_event_categories', 'ee_event_categories' );
?>

Upon clicking on the resulting buttons from the previous function, a custom WP_Query runs and displays posts that match the criteria in the function below. This function resides in functions.php. I think I have to pass the $paged variable from the load_events_by_category() function into the javascript code. Unfortunately, I'm at a loss as to how to do it. Maybe the $paged variable needs to be applied as a second key / value pair in the wp_localize_script() declaration? Now I'm thinking out loud.

<?php
function load_events_by_category() {
  $paged = ($_POST['paged']) ? $_POST['paged'] : 1;
  $taxonomy = $_POST['taxonomy'];
  $slug = $_POST['slug'];
  $term_id = intval($_POST['term_id']);
    $category_events_args = array(
      'post_type'       => 'tribe_events',
      'posts_per_page'  => 4,
      'post_status'     => 'publish',
      'eventDisplay'    => 'custom',
      'order'           => 'ASC',
      'paged'           => $paged,
      'tax_query' => array(
        array(
          'taxonomy' => 'tribe_events_cat',
          'field'    => 'term_id',
          'terms'    => $term_id
        )
      )
    );
    $catquery = new WP_Query( $category_events_args );
    ob_start(); 
    if( $catquery->have_posts() ) : ?>
      <div class="this-weeks-events">
        <div class="featured-events-grid">
          <?php while ( $catquery->have_posts() ) : $catquery->the_post(); ?>
            <div class="featured-events-grid-child">
              <div class="event-date"
                data-taxonomy="<?php echo $taxonomy ?>"
                data-slug="<?php echo $slug; ?>" 
                data-term-id="<?php echo $term_id; ?>" 
                style="background:<?php echo the_field('event_category_background', $taxonomy . '_' . $term_id ); ?>"
              >
                <p class="event-day"><?php echo tribe_get_start_date( $event_id, false, 'D' ); ?></p>
                <p class="event-start-date" style="color:<?php echo the_field('event_date_color', $taxonomy . '_' . $term_id ); ?>"><?php echo tribe_get_start_date( $event_id, false, 'j' ); ?></p>
                <p class="event-month"><?php echo tribe_get_start_date( $event_id, false, 'F' ); ?></p>
              </div><!-- end div event-date -->

              <?php if( has_post_thumbnail() ) : ?>
                <div class="featured-image">
                  <a href="<?php echo the_permalink(); ?>"><?php the_post_thumbnail( 'full' ); ?></a>
                </div><!-- end div featured-image -->
              <?php endif; ?>
              <div class="featured-events-details-grid">
                <div><h2><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h2></div>
                <div>
                  <i class="far fa-clock" aria-hidden="true"></i>
                  <?php echo tribe_get_start_time( $event_id ); ?>
                  -
                  <?php echo tribe_get_end_time( $event_id ); ?>
                  <?php if( tribe_is_recurring_event() ) : ?>
                    <p class="event-recurring"><img src="<?php echo get_stylesheet_directory_uri() . '/images/arrows-rotate.webp' ?>" alt="rotating arrow icon for weekly events" width="20" height="20" /> Weekly Event</p>
                  <?php endif; ?>
                </div>
              </div><!-- end div featured-events-details-grid -->
            </div><!-- end div featured-events-grid-child -->
          <?php endwhile; ?>
        </div><!--end featured events grid -->        
        <?php
          $nextpage = $paged+1;
          $previouspage = $paged-1;
          $total = $catquery->max_num_pages;
          $pagination_args = array(
            'base'                => '%_%',
            'format'              => '?paged=%#%',
            'total'               => $total,
            'current'             => $paged,
            'show_all'            => false,
            'end_size'            => 1,
            'mid_size'            => 2,
            'prev_next'           => true,
            'prev_text'           => __('<span class="prev" data-attr="'.$previouspage.'">&laquo;</span>'),
            'next_text'           => __('<span class="next" data-attr="'.$nextpage.'">&raquo;</span>'),
            'type'                => 'plain',
            'add_args'            => false,
            'add_fragment'        => '',
            'before_page_number'  => '',
            'after_page_number'   => ''
          );
          $paginate_links = paginate_links($pagination_args);

          if ($paginate_links) : ?>
            <div id='pagination' class='pagination'>
              <?php echo $paginate_links; ?>
            </div>
          <?php endif; ?>
      </div><!-- end div this weeks events -->
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
    <?php
      $content = ob_get_clean();
      echo $content;
      die();
}
add_action( 'wp_ajax_load_events_by_category', 'load_events_by_category' );
add_action( 'wp_ajax_nopriv_load_events_by_category', 'load_events_by_category' );
?>

I'm not sure if this is important but I'll include it anyway. It's how I'm using wp_localize_script, also located in functions.php.

<?php wp_enqueue_script( 'ajax-load-category-events', get_stylesheet_directory_uri() . '/dist/ajax-category-events.js', array( 'jquery' ), '1.0', true ); 
wp_localize_script( 'ajax-load-category-events', 'categoryevents', array(
  'ajaxurl'   => admin_url( 'admin-ajax.php' )
));
?>

And finally, here's the code in above javascript file.

(function ($) {
  $(".category-block button").on('click', function (e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: categoryevents.ajaxurl,
      data: {
        action: 'load_events_by_category',
        taxonomy: $(this).data('taxonomy'),
        slug: $(this).data('slug'),
        term_id: $(this).data('term-id')
      },
      success: function (html) {
        $('#fl-main-content').find('#event_results .fl-rich-text').empty();
        $('#event_results .fl-rich-text').append(html);
      },
      error: function (error) {
        console.log("Error: ", error)
      }
    })
  });
})(jQuery);

I actually did try passing the $paged variable into the script vars of the wp_localize_script declaration. I thought that would at least make the javascript "aware" of what page of results were showing.

wp_localize_script( 'ajax-load-category-events', 'categoryevents', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'paged' => $_POST['paged'] ? $_POST['paged'] : 1; ));

I also spent hours upon hours reviewing similar SO questions and looking for tutorials on how to solve this problem. I'll be darned but it doesn't seem using ajax pagination inside ajax produced content is much of a thing.

Share Improve this question asked Feb 15 at 23:02 ChrisChris 231 silver badge3 bronze badges New contributor Chris is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

1 Answer 1

Reset to default 0

If you are loading the posts and pagination via ajax, then your pagination links need have listeners attached to them that make ajax calls of their own. Right now, it appears you are loading normal pagination links, and that's not how your page is designed to work.

Three steps:

  1. Add a 'paged' variable to the data object in your ajax call so that this information is passed to your php function.
  2. Adjust your php function so that it outputs custom pagination links
  3. Add new javascript that listens for clicks on these links and makes your ajax call with the paged variable set appropriately

EDIT: On second thought, you don't need step two as you can probably attach your event and gather the page information from the links as they are.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论