0

How do I change this code to link each title to the post?

Specifically - this line:

$dl .= '<dt>' . $query->post->post_title . '</dt>';

Thanks,

<?php
$args = array(
    'post_type' => 'my_glossary_term',
    'orderby' => 'title',
    'order' => 'ASC',
    'posts_per_page' => -1
);

$query = new WP_Query( $args );

$dl = '';
$glossary_letter = '';
$active_letters = array( );

while ( $query->have_posts() ) {
    $query->next_post();
    $term_letter = strtoupper( substr( $query->post->post_title, 0, 1 ) );
    if ( $glossary_letter != $term_letter ) {
        $dl .= (count( $active_letters ) ? '</dl>' : '') . '<li id="' . $term_letter . '"><span class="subheading">' . $term_letter . '</span><dl>';
        $glossary_letter = $term_letter;
        $active_letters[] = $term_letter;
    }
    $dl .= '<dt>' . $query->post->post_title . '</dt>';
    $dl .= '<dd>' . $query->post->post_content . '</dd>';
}
$dl .= '</dl></li>';

$ul = '<ul class="letters">';
foreach ( array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ) as $letter ) {
    $ul .= '<li>' . (in_array( $letter, $active_letters ) ? '<a href="#' . $letter . '">' . $letter . '</a>' : $letter) . '</li>';
}
$ul .= '</ul>';

echo '<div id="glossary">' . $ul . '<ul class="definitions">' . $dl . '</ul></div>';
?>
2
  • Thanks - that worked great. Changed the code per your suggestion. Louise
    – Louise
    Commented Oct 27, 2013 at 18:32
  • It is not clear who you are talking to.
    – s_ha_dum
    Commented Oct 27, 2013 at 23:01

1 Answer 1

2

Following your code strictly you'd want ...

$dl .= '<dt><a href="'.get_permalink($wp_query->post->ID).'">' . $wp_query->post->post_title . '</a></dt>';

... but you are using the WP_Query object in a very atypical way. You are sort-of brute forcing your way through the Loop instead of using the methods and template functions built into the core. For example:

while ( $query->have_posts() ) {
    $query->the_post();
    $term_letter = strtoupper( substr( get_the_title(), 0, 1 ) );
    if ( $glossary_letter != $term_letter ) {
        $dl .= (count( $active_letters ) ? '</dl>' : '') . '<li id="' . $term_letter . '"><span class="subheading">' . $term_letter . '</span><dl>';
        $glossary_letter = $term_letter;
        $active_letters[] = $term_letter;
    }
    $dl .= '<dt><a href="'.get_permalink().'">' . get_the_title() . '</a>></dt>';
    $dl .= '<dd>' . get_the_content() . '</dd>';
}
$dl .= '</dl></li>';

Or at the very least you can replace $query->post-> with $post-> since the the_post() method resets the $post global to the next post in the loop each time it runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.