I've got this code:
<?php wp_dropdown_categories(); ?>
And I've got this code from Codex:
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo esc_url( home_url( '/' ) ); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
First function takes all categories, and second function displays them on select. When I select one of the categories, then I'm redirected to the URL of the chosen category.
My problem is, that loop doesn't show posts from chosen category. Searching for a solution, I came across something like this:
$query = new WP_Query( array( 'category_name' => 'staff' ) );
But it works only for things like "XYZ Category page". My page allows creating new categories by end user, so I need something more dynamically.
Maybe something like this?
$cat = get_the_category();
$query = new WP_Query( array( 'category_name' => $cat ) );
and then use it in loop?
EDIT: This is my code that I used in loop (both category.php and archive.php
<?php
query_posts(array('posts_per_page' => 2, 'paged' => $paged));
$queryObject = new Wp_Query( array(
'posts_per_page' => 2,
'post_type' => array('post'),
'paged' => $paged,
'orderby' => 1,
));
if ( $queryObject->have_posts() ) {
while ( $queryObject->have_posts() ) {
$queryObject->the_post();
?>
<div class="shorts">
<div class="shorts1">
<a class="Text3" href="<?php the_permalink(); ?>"><strong><?php the_title(); ?></strong></a>
<br><br>
<a class="Text2"><?php the_excerpt() ?></a>
<br><br>
<div class="more-wrapper">
<div class="more">
<a href="<?php the_permalink(); ?>">Dowiedź się więcej</a>
</div>
</div>
</div>
</div>
</article>
<?php }} ?>
You don't really need to define a custom query in category.php . WordPress is clever enough to do that for you. Just replace
<?php
query_posts(array('posts_per_page' => 2, 'paged' => $paged));
$queryObject = new Wp_Query( array(
'posts_per_page' => 2,
'post_type' => array('post'),
'paged' => $paged,
'orderby' => 1,
));
if ( $queryObject->have_posts() ) {
while ( $queryObject->have_posts() ) {
$queryObject->the_post();
?>
With
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
$categories = get_query_var('cat');
if (!empty($categories))
{
$category = get_category($cat);
$categoryName = $category->name;
$categorySlug = $category->slug;
$catId = $category->cat_ID;
}
$args = array(
'posts_per_page' => 12,
'post_type' => 'post',
'order' => 'ASC',
'paged' => $paged,
'tax_query' => array(
array (
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $categorySlug
)
));
$query = NEW WP_Query($args);