on my WordPress site, I’m developing a glossary list of novel writing terms, using tags and tags descriptions to draw definitions from. Currently, when any tag has more than 0 posts associated with it, it will link to that tag’s archive page, allowing readers to further read up on the topic.

What I would like to achieve, is to have any tag that has exactly 1 post associated with it, to link directly to that post rather than the tag archive. I’ve been looking around for a solution, but can’t seem to find any way to achieve that.

Any help would be greatly appreciated!

For reference, this is the current code:

<!-- Add glossary list in content -->
<?php foreach ( $groups as $group ): ?>
    <ul>
    <div class="glossary-title-link" id ="section-<?php echo str_replace(' ', '-', strtolower($group['name'])) ?>">
    <h4 id ="<?php echo $group['name'] ?>"><?php echo $group['name'] ?></h4>
    </div>
    <?php foreach ( $group['tags'] as $tag ): ?>
        <li class="glossary-list">

        <!-- If there are any posts for the tag, link to the tag page -->
        <?php

            if ( $tag['count'] > 0 ) {
                echo '<a class="glossary-link" id="term-';
                echo str_replace(' ', '-', strtolower($tag['name']));
                echo '" href="';
                echo $tag['link'];
                echo '">';
                echo $tag['name'];
                echo '</a></br>';


            } else {
                echo '<div class="glossary-link" id="term-';
                echo str_replace(' ', '-', strtolower($tag['name']));
                echo '">';
                echo $tag['name'];
                echo '</div>';

            }
        ?>
        <?php echo $tag['description'] ?></li>

    <?php endforeach; ?>
    </ul>
<?php endforeach; ?>

Which leads to this, where ‘cliffhangers’ is linked and ‘denouement’ is not:

1 Answer
1

try this ( untested and assuming of course that $tag is the right object tag and $tag[‘count’] is the number of post with that tag ):

if ( $tag['count'] > 1 ) {
 //first part of your code
}
else if($tag['count'] == 1){
  $the_query = new WP_Query( 'tag='.$tag['name'] );
  if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
      $the_query->the_post();
      echo '<a href="';
      echo get_the_permalink();
      echo '">';
      echo $tag['slug'];
      echo '</a></br>';
    }
  }
  wp_reset_query();
}
else{
//// last part of your code
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *