How to view posts from a specific year through URL (?year=2016)?
-
I’m still learning PHP, so I apologize if this is a dumb question.
I’ve been trying to figure out how to make a form that will allow to view posts only from a specific year. I know that WP_Query has the ability to do this using “year”, but how do you do it through a URL? For instance, like going to https://site.com/custom-post-type/?orderby=date&order=DESC&year=2015 would show all posts from 2015, in descending order by date. Is this not how it should work?
So, I want a select dropdown that gets populated with all of the posts from a specific custom post type’s years. There are currently only posts from 2015 and 2016 in this CPT, so 2015 and 2016 should be in the dropdown. And when you click 2016, and submit, it should then display only the CPT posts from 2016.$args = array( 'post_type' => array('plant'), // display only Plants; otherwise, every post type is shown 'orderby' => $order_by, // this comes from a select, options of date, title, menu_order, and random currently 'order' => $order, // this comes from a select, ASC and DESC are the options 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'year' => $year, // here lies the issue. If I hard code in 2015 here, it works on the page itself but not through the URL. How to pass into this through the URL? ); // The Loop $loop = new WP_Query( $args ); if ( $loop->have_posts() ) : ?>
The form (currently broken for the year):
<form action="" method="get"> <div class='post-filters'> Sort by: <select name="orderby"> <?php $orderby_options = array( 'menu_order' => 'Default Sort', 'date title' => 'Date', // 'post_date' => 'Order by Date', 'title' => 'Title', // 'post_title' => 'Order by Title', 'rating' => 'Rating', 'company' => 'Company', 'rand' => 'Random', ); foreach ($orderby_options as $value => $label) { echo "<option ".selected( $_GET['orderby'], $value )." value='$value'>$label</option>"; } ?> </select> Order: <select name="order"> <?php $order_options = array( 'ASC' => 'Ascending', 'DESC' => 'Descending', ); foreach ($order_options as $value => $label) { echo "<option ".selected( $_GET['order'], $value )." value='$value'>$label</option>"; } ?> </select> Year: <select name="year"> <option value="any">All</option> <?php global $post; // found this snippet elsewhere to populate the post years... is there a better method? $query = 'post_type=plant&numberposts=-1&orderby=date&order=DESC'; $myposts = get_posts($query); foreach($myposts as $post) { $year = get_the_time('Y'); $years[] = $year; } $years = array_values( array_unique( $years ) ); foreach ( $years as $year => $label) { echo "<option ".selected( $_GET['year'], $year )." value='$year'>$label</option>"; } ?> </select> <input type="submit" value="Submit" /> </div> </form>
I’ll probably take a break and come back later and it will slap me in the face… but I’m stumped.
- The topic ‘How to view posts from a specific year through URL (?year=2016)?’ is closed to new replies.