Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Display post loop associated with current category url slug WordPress

  • SOLVED

Hi There,

I have to display posts dependent on what category slug the user is on.

For example:

- If the user is on a page www.me.com/topic/wheels. Then they will only see posts of topic wheels.

- If the user is on a page www.me.com/topic/rubber. Then they will only see posts of topic rubber.

Since there are 100's of topics - I would need a code snippet that retrieves the current url topic slug and then displays the posts associate to that current url topic slug.

Below is what I had in mind but not sure if this is the best way of doing this:

<?php
$term = get_queried_object();
echo $term->slug;
if (have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<ul>
<li><?php the_title(); ?> </li>
</ul>
<?php endwhile; ?>
<?php endif; ?>



Please let me know of any suggestions - very much appreciated.

Answers (3)

2022-05-24

Arnav Joy answers:

Please try this

<?php

$term = get_queried_object();

$args = array(
'post_type' => 'post',
$term->taxonomy => $term->slug,

);


$the_query = new WP_Query( $args );

if ($the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<ul>
<li><?php the_title(); ?> </li>
</ul>
<?php endwhile; ?>
<?php endif; ?>


Arnav Joy comments:

If above code doesn't work then try replacing taxonomy name with actual name in this line

$term->taxonomy => $term->slug,

so if name of the taxonomy is category then this line will be:

'category' => $term->slug,

and final $args will be

$args = array(
'post_type' => 'post',
'category' => $term->slug,
);

2022-05-24

timDesain Nanang answers:

Hi, you can use Tags as Topic
set Tag base = topic
under Settings - Permalinks menu
https://your-domain/wp-admin/options-permalink.php


timDesain Nanang comments:

if you want to dig up about WordPress template hierarchy, then check https://wphierarchy.com/

2022-05-24

Francisco Javier Carazo Gil answers:

This is how WordPress works actually.

Are you using the archive taxonomy? There you will have it done.