Wordpress: dynamically sort content when a button / link is clicked

I need a little help with some features. I am trying to create a mail page that can be sorted dynamically to show which messages the user would like to see.

Usage scenario:

There are 4 ei names in the message: Title A, Title B, Title C and Title D.

Name A = CARAMOAN A LOOK BACK;

Name B = PURPOSE: PRERCESA PUERTO;

Name C = THINGS A FREE ROUND PARTY TICKET MAY MAKE YOU SEE;

Name D = FIVE THINGS TO REMEMBER WHEN TRAVELING IN PHILIPPINES;

Now with this I want to sort by:

Most comment

Most Popular

Alphabetically - Ascending

which the user can change the order of the pages by clicking a button that will look something like this.

enter image description here

+4
source share
1 answer

The easiest way to do this is to use a query string.

I assume you are looking at the category page.

First, we will add buttons to the category page.

<a href="?sortby=comment>Sort by Comment</a> <a href="?sortby=views>Sort by Views</a> <a href="?sortby=alphabet>Alphabetical</a> 

This adds a query string to the page URL, now at the top of the category page we will add this code:

 <?php if (array_key_exists("sortby", $_GET) === true) { $newQuery = sortIt($_GET['sortby']); } ?> 

After that, we will create a function that sorts the messages for us in the functions.php template

Since we have 3 types of sorting, we can use a switch case or an if-else statement. I will use if-else here.

 <?php function sortIt($sortType) { global $wp_query; $cat_ID = get_query_var('cat'); if (strcmp($sortType, 'comment') == 0 ) { $newQuery = new WP_Query( array( 'orderby' => 'comment_count' , 'cat' => $cat_ID, 'posts_per_page' => '10') ); } if (strcmp($sortType, 'views') == 0 ) { $newQuery = new WP_Query( array( 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'order'=> 'DESC', 'cat' => $cat_ID, 'posts_per_page' => '10') ); } if (strcmp($sortType, 'alphabetical') == 0 ) { $newQuery = new WP_Query( array( 'orderby' => 'title' , 'cat' => $cat_ID, 'posts_per_page' => '10') ); } return $newQuery; } ?> 

Wordpress does not have its own view count, I used the instructions that I read here .

Since we have all the necessary functions and variables, we need to redefine the request.

You will edit the loop so that it looks like this:

 <?php if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post(); ?> 

What is it:)

+2
source

Source: https://habr.com/ru/post/1403188/


All Articles