WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Displaying sticky post titles only from one category

[Resolved] Displaying sticky post titles only from one category

  • 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>';
    };
    ?>

Viewing 4 replies - 1 through 4 (of 4 total)
  • 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>';

    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

    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’.

    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.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Displaying sticky post titles only from one category’ is closed to new replies.
Skip to toolbar