treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Display limited number of Custom Post Types titles in sidebar.

  • Hi there

    I have a couple of different custom post types in my site - for job vacancies and tenders respectively. I need to display just the titles of of each post in a particular post type in the the sidebar.

    I have done so by using the following:

    <section>
    <?php $sidebar_vacancies_loop = new WP_Query( array( 'post_type' => 'vacancies', 'posts_per_page' => 3 ) ); ?>
    <header>
    <h3><span>Vacancies</span></h3>
    <p><a href="<?php bloginfo('url'); ?>/vacancies/">View all <span>job openings</span></a></p>
    </header>
    <ul>
    <?php while ( $sidebar_vacancies_loop->have_posts() ) : $sidebar_vacancies_loop->the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    </ul>
    </section>


    This works well, but I need to display alternate content if there are no vacancies.
    • Either by having an alternate li that simply says, 'No vacancies'
    • Or just not displaying the entire section if there are none.

    Any help would be appreciated.

    Thanks in advance.
  • How about:

    <?php if($sidebar_vacancies_loop->have_posts()):?>
    <?php while ( $sidebar_vacancies_loop->have_posts() ) : $sidebar_vacancies_loop->the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    <?php else:?>
    <li>No vacancies</li>
    <?php endif;?>
  • I got this working eventually. Pretty similar to the above, so thanks ddliu.