0
votes

I have a question related to WordPress. I have made a dropdown of custom taxonomies on single.php page That's the code I am using to list my taxonomies:

       <ul class="dropdown-menu" aria-labelledby="dLabel">
          <?php $terms = get_terms( array(
                'taxonomy' => 'subject',
                'hide_empty' => false,
                            ) );
            if( !empty( $terms ) ):
            foreach ($terms as $key => $value) :
                $term = $value->name;
         ?>
         <li><a href=""><?php echo $term; ?></a></li>
         <?php endforeach; endif; wp_reset_query();  ?>
      </ul>

Right now all taxonomy in dropdown have the same post link that is opend on the page. I want that every taxonomy should have the link of it's respective first post and when I click on a taxonomy it open that taxonomy's first post on the same single.php page. Is there any way of doing that? Here is the picture of my page: enter image description here

That's how my taxonomy dropdown look like if you zoom and look in the bottom left corner you will see the current post link that is showing on all subject names is there any way that I can change this link to that subject's first post link. Right now biology taxonomy post is open when I click on chemistry first post of chemistry open on this page. Please help me in doing this task I'll be very thankful to you.

1

1 Answers

1
votes

After having the term-object, you can lookup the first post and get its permalink. in my example i ordered by date desc. Then set the link of the post:

<ul class="dropdown-menu" aria-labelledby="dLabel">
    <?php
    $terms = get_terms(array(
        'taxonomy' => 'subject',
        'hide_empty' => false,
    ));
    if (!empty($terms)):
        foreach ($terms as $key => $value) :
            $term = $value->name;

//get the first post of this term **
            $args = array(
                'post_type' => 'post',
                'orderby' => 'date',
                'order' => 'DESC',
                'numberposts' => 1,
                'post_status'      => 'publish',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'subject',
                        'field' => 'id',
                        'terms' => $value->term_id,
                    )
                )
            );
            $posts=get_posts($args);
            $first_page_link = get_permalink($posts[0]->ID);
//**
            ?>
            <li><a href="<?= $first_page_link; ?>"><?= $term ?></a></li>
        <?php endforeach;
    endif;
    wp_reset_query(); ?>
</ul>
<?php

The code is not tested. And of course, you should do some checks, like what to do when no post is available with that term.