false-hero false-hero - 1 month ago 9
PHP Question

Wordpress: Let user select the number of posts shown per page

I'm trying to build a function where the visitor can select the number of posts shown per page like this:

enter image description here

Where do I start and how do I achieve this? I am currently using query_post to list all the posts:

<?php
$paged = 1;
query_posts(array( 'showposts'=> 10, 'post_type' => 'post', 'category_name' => 'jobseeker-announcements', 'order' => 'DESC', 'posts_per_page' => 10, 'paged' => get_query_var('paged'))); ?>
<?php while (have_posts()) : the_post(); ?>
<div class="post-list">
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p class="datetime"><span>Date Posted:</span> <?php the_time('m/j/Y'); ?></p>
<p><?php the_excerpt(); ?></p>
<!--/post-list--></div>
<?php endwhile; ?>

Answer

Use jquery change function.

 <?php 
if(isset($_GET['pageVal'])){
  $showposts = esc_sql($_GET['pageVal']);
}else{
  $showposts = 10;
}
    $paged = 1;
    query_posts(array( 'showposts'=> $showposts, 'post_type' => 'post', 'category_name' => 'jobseeker-announcements', 'order' => 'DESC', 'posts_per_page' => $posts_per_page, 'paged' => get_query_var('paged'))); ?>
    <?php while (have_posts()) : the_post(); ?>
    <div class="post-list">
        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <p class="datetime"><span>Date Posted:</span> <?php the_time('m/j/Y'); ?></p>
        <p><?php the_excerpt(); ?></p>
    <!--/post-list--></div>
    <?php endwhile; ?>

<select class='page-select'>
<option value='10'>10</option>
<option value='10'>20</option>
<option value='10'>30</option>
</select>
<script>
jQuery.ready(function(){
 $('.page-select').change(function(){
  $(location).attr('href', window.location.href+'?pageVal='+$('.page-select').val());
});
});
</script>