Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Zeshan Ahmed
Zeshan Ahmed
13,151 Points

Blog Sorting - Recent Posts, Popular Posts and All

Hi Guys,

Inside the blog of my WordPress site, there is needed sorting of 3 things:

  1. Most Recent Posts
  2. Most Popular Posts
  3. All Posts

Screenshot: http://prntscr.com/674cfo; (1) so once the user click "Most Recents Posts" the recent posts should be displayed (on new page). (2) If use clicks the "Most Popular Posts", the most viewed posts will display and for "All Posts" we can use "posts_per_page=-1".

The only thing I'm confused with is which approach should I use to achieve this? I can take care of any JS task, just confusing how to rewrite rules (if needed) and etc.

I have tried this code in index.php:

$filter = $_GET['filter'];

if ( $filter == 'all' ) {
  query_posts( $query_string . '&posts_per_page=-1');
} elseif ( $filter == 'most-popular' ) {
  query_posts( $query_string . '&orderby=rand&posts_per_page=1');
}

while (have_posts()) : the_post(); 

And this in functions.php file:

// Rewrite Rules for Blog Filtering
add_action('init','add_author_more_rewrite_rule');

function add_author_more_rewrite_rule() {
  add_rewrite_rule(
    'blog/filter/(\d*)$',
    'index.php?filter=$matches[1]',
    'top'
  );
}

But this doesn't seem to work? However I'm getting correct results when going to url "/blog/?filter=most-popular" but pagination doesn't seem to work and redirecting to 404 page. Any ideas?

Thanks a lot!