I have 3 tags:
- Tag 1
- Tag 2
- Tag 3
I need to display all of the posts in my custom post type
and specified term. They need to be sorted by tag
and hiding the tags that are not being used like this:
Tag 1
- Post A
- Post C
- Post A
Tag 2
- Post B
- Post B
But it's displaying like this:
Tag 1
- Post A
- Post C
- Post A
Tag 2
- Post B
- Post B
Tag 3
- (Empty)
Tag 3 is being displayed even though there are no posts currently using the tags...
Here is the code I'm using:
// These 3 variables change dynamically depending on page slug.
$cpt = houses;
$tax = type;
$term = small;
$args = array(
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC',
'post_type' => $cpt,
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'name',
'terms' => $term
)
)
);
$tags = get_tags($args); // Tag 1, Tag 2, Tag 3
$posts = get_posts($args);
foreach($tags as $tag)
{
?>
<h5><?php echo $tag->name.' (Tag)'; ?></h5>
<?php
foreach($posts as $post)
{
if( has_tag( $tag ) )
{
?>
<a href="<?php echo the_permalink();?>"><?php echo the_title().' (Post)';?></a><br>
<?php
}
}
?>
<hr>
<?php
}
?>
I appreciate the help!
My Answer:
-1,
'post_type' => $cpt,
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $term
)
)
);
$query = new WP_Query($args);
if($query->have_posts()) {
$current_tag = '';
while($query->have_posts()) {
$query->the_post();
$tags = get_the_tags();
if($tags) {
foreach($tags as $tag) {
if($tag->name != $current_tag) {
$current_tag = $tag->name;
echo '
' . $current_tag . '
';}
echo '
' . get_the_title() . '
';}
}
}
} else {
echo 'No posts found';
}
wp_reset_postdata();
Rate this post
4 of 5 based on 3331 votesComments