Im trying to get the category ID from wp_dropdown_categories();
and then pass the ID into a loop to have it output posts titles from that particular category.
I currently have this:
<form action="<?php bloginfo('url'); ?>" method="get">
<?php wp_dropdown_categories(); ?>
</form>
<div class="cat-list">
<ul>
<?php
global $post;
$args = array( 'posts_per_page' => 5, 'category' => $_GET['value']);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) :
setup_postdata( $post ); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;
wp_reset_postdata(); ?>
</ul>
</div>
But it’s not grabbing the category ID from the $_GET['value']
and I’m not sure what I need to do to get it to pass that ID to the array.
Eventually, I’d like to have it so that when you select a different category that it will show the posts associated with that selected category.
But I figured that I’d try to get the select to work first and then move on from there.
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: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 toPOST
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 thename
parameter towp_dropdown_categories()
and choose a unique name, in above example like this: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.
The
$_GET['value']
is related to theNAME
attribute from yourSELECT
. The select name can be changed using thename parameter
in thewp_dropdown_categories()
function too. Useprint_r($_GET);
to see what values your form is submitting and then use them in yourget_posts()
query.You can print your id echo $termss->term_id in drop down