• I want to display links to each post outside of the Loop.

    This code works:

    <ul class="nav">
    <li><a href="#how"> <?php echo get_the_title(6); ?> </a></li>
    <li><a href="#logistics"> <?php echo get_the_title(9); ?> </a></li>
    <li><a href="#who"> <?php echo get_the_title(11); ?> </a></li>
    <li><a href="#tips"> <?php echo get_the_title(13); ?> </a></li>
    </ul>

    But, it’s calling the title based on the post ID. I want to call the title based on the slug. Any way to do that?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hmmm… I think something like this would work:

    <li><a href="#how"> <?php $page = get_page_by_path($slug); echo get_the_title($page->ID); ?> </a></li>

    Just substitute the $slug variable with your slug name (wrapped in single quotes like this… ‘slug’).

    You will need to do this for each one of your <li> items.

    Thread Starter umdechai

    (@umdechai)

    Hi, thanks for your reply.

    <ul class="nav">
    <li><a href="#how"> <?php $page = get_page_by_path('first-link'); echo get_the_title($page->ID); ?> </a></li>
    <li><a href="#how"> <?php $page = get_page_by_path('second-link'); echo get_the_title($page->ID); ?> </a></li>
    </ul>

    I tried the code above but it’s just displaying the title of my most recent post for both
    <li> items.

    Thread Starter umdechai

    (@umdechai)

    I was able to do it with multiple loops in my navbar, and query_posts. Is that a good idea? It works, but I’m not sure if there’s a better way. It seems like an awful lot of code.

    <ul class="nav">
    
    <li>
    <?php query_posts('name=first-link&posts_per_page=1'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <a href="#how"> <?php the_title() ;?> </a>
    <?php endwhile; else: ?>
    <?php endif; wp_reset_query(); ?>
    <?php rewind_posts(); ?>
    </li>
    
    <li>
    <?php query_posts('name=second-link&posts_per_page=1'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <a href="#logistics"> <?php the_title() ;?> </a>
    <?php endwhile; else: ?>
    <?php endif; wp_reset_query(); ?>
    <?php rewind_posts(); ?>
    </li>
    
    <li>
    <?php query_posts('name=third-link&posts_per_page=1'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <a href="#who"> <?php the_title() ;?> </a>
    <?php endwhile; else: ?>
    <?php endif; wp_reset_query(); ?>
    <?php rewind_posts(); ?>
    </li>
    
    <li>
    <?php query_posts('name=fourth-link&posts_per_page=1'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <a href="#tips"> <?php the_title() ;?> </a>
    <?php endwhile; else: ?>
    <?php endif; wp_reset_query(); ?>
    <?php rewind_posts(); ?>
    </li>
    
    </ul>
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Display post title from page slug’ is closed to new replies.