WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Displaying sticky post titles only from one category (5 posts)

  1. waylaid
    Member
    Posted 2 years ago #

    Hi

    I'm trying to add the titles of some sticky posts to the side bar of one of my templates.

    The functionality I want is: If there is/are sticky post/s in the news category (cat 5 in this case) then the sidebar will display a header, 'Sticky posts', and list the titles of each sticky post. If there are no sticky posts in the news category then no header or list of posts will appear.

    The closest I've got is with the basic wordpress code below which works fine except if there is a sticky post in another category then the header still displays (but no list of posts) because the get__option code looks for any sticky posts.

    I've tried other solutions but with those if no sticky post is found then all post titles are displayed instead.

    Any ideas?

    Thanks
    Russell

    code:

    <!-- sticky posts -->
    <?php $sticky = get_option( 'sticky_posts' );
    $args = array(
    	'post__in'  => $sticky, 'cat' => '5'
    );
    query_posts( $args );
    
    if ( $sticky[0] ) {
    echo '<h3>Sticky posts</h3>
    <ul>';
    while ( have_posts() ) : the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile;
    
    echo '</ul>';
    };
    ?>
  2. vtxyzzy
    Member
    Posted 2 years ago #

    Try replacing everything after the query_posts() with this:

    $found = false;
    while ( have_posts() ) : the_post();
       if ( in_category(5) ) :
          if ( !$found) :
             $found = true;
             echo '<h3>Sticky posts</h3>
             <ul>';
          endif; ?>
          <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
       <?php endif;
    endwhile;
    if ( $found ) echo '</ul>';
  3. waylaid
    Member
    Posted 2 years ago #

    Thankyou very much.

    I had to put the part

    if ( $sticky[0] ) {

    back in because when there were no sticky posts it listed all news titles instead but otherwise it works like a dream

    I much appreciate your help.
    Russell

  4. vtxyzzy
    Member
    Posted 2 years ago #

    One other suggestion: For better efficiency, put the query_posts() after if ( $sticky[0] ) {, so the query will not be run if there are no stickies.

    Also, please use the dropdown on the right to mark this topic 'Resolved'.

  5. waylaid
    Member
    Posted 2 years ago #

    One other suggestion: For better efficiency, put the query_posts() after if ( $sticky[0] ) {, so the query will not be run if there are no stickies.

    Great, have done that and will mark as resolved.

    Thanks again.

Topic Closed

This topic has been closed to new replies.

About this Topic