You’re on the right track with using a form
, the only thing you’re missing, you have to submit what you have selected. For example like this:
<form method="GET" action="">
<div>
<?php
$select = wp_dropdown_categories('show_option_none=Select category&orderby=name&echo=0');
$select = preg_replace("#<select([^>]*)>#", "<select$1 onchange="return this.form.submit()">", $select);
echo $select;
?>
<noscript>
<div>
<input type="submit" value="View" />
</div>
</noscript>
</div>
</form>
Code adapted from the example section of the wp_dropdown_categories() codex page, there are other examples, take a look. I changed one thing, the form action is empty, because we want to stay on the page.
The variable you want would be $_GET['cat']
; additionally you can visually see that by looking to the browser address bar, there is now something like this ?cat=1
, a query string, after you selected a category. If you don’t want the query string to show, you actually can change the form method to POST
and the variable to $_POST['cat']
.
Edit:
On the home page this will redirect to the category archive, because wordpress reacts to the query string cat
. In this case you have to add the name
parameter to wp_dropdown_categories()
and choose a unique name, in above example like this:
wp_dropdown_categories('show_option_none=Select category&orderby=name&echo=0&name=uniquename');
which leads to the variable name being $_GET['uniquename']
or $_POST['uniquename']
.
2nd Edit:
On first page load there is no $_GET[‘uniquename’] variable set, so your get_posts query will, will operate with an empty value, which leads to all post been shown. To prevent this setup a variable like shown below and use it in your arguments array.
$gp_cat = (isset($_GET['uniquename']) ? $_GET['uniquename'] : '5');
$args = array( 'posts_per_page' => 5, 'category' => $gp_cat);