Remove Sticky Posts from Recent Posts List

Discussion in 'WordPress' started by m0nk3y, Jan 16, 2011.

  1. #1
    Hi

    I am using the plugin Advanced Category Excluder Widgets which allows me to remove certain categories from certain content types (pages, categories, posts, feeds, etc), therefore I have removed a category I do NOT want to show in Recent Posts using this plugin.

    However, it doesn't remove Sticky posts, even if the Sticky post is in a Category I have excluded.

    Here's the code, does anybody know how to exclude Sticky posts (I basically want Recent Posts to ignore Sticky posts altogether). I have confirmed the problem is because the post is 'Sticky' (my theme needs to use sticky posts to show posts I want 'highlighted' at the top of my homepage) by unselecting the post as Sticky - the post is then hidden because it is in a Category which has been Excluded using this plugin. When I re-enable Sticky, the post is shown in Recent Posts list again.

    <?php
    /*
    Plugin Name: Advanced Category Excluder Widgets
    Version: 1.3.1.1
    Plugin URI: http://advanced-category-excluder.dev.rain.hu
    Description: This plugin adds some basic widgets that support category exclusion
    Author: DjZoNe
    Author URI: http://djz.hu/
    */
    
    /** 
      * The display code is from includes/widgets.php from version 2.6
      */
    
    class AceRecentPostsWidget 
    {
      /**
       * Default values
       */
      
      var $title = '';
      var $count = '0';
      var $hierarchical = '0';
      var $dropdown = '0';  
    
      // static init callback
      function init() 
      {
        // Check for the required plugin functions. This will prevent fatal
        // errors occurring when you deactivate the dynamic-sidebar plugin.
        if ( !function_exists('register_sidebar_widget') )
          return;
    
        $widget = new AceRecentPostsWidget();
    
        // This registers our widget so it appears with the other available
        // widgets and can be dragged and dropped into any active sidebars.
        register_sidebar_widget('ACE Recent Posts', array($widget,'display'));
    
        // This registers our optional widget control form.
        register_widget_control('ACE Recent Posts', array($widget,'control'), 280, 300);
      }
    
      function control() {
        // Get our options and see if we're handling a form submission.
        $options = get_option('ace_widget_recent_posts');
          
        if ( !is_array($options) )
          $options = array('title'=>'',
                   'count' => $this->count,
                   'hierarchical' => $this->hierarchical,
                   'dropdown' => $this->dropdown );
        
        
        if ( !empty($_POST['ace-recent-posts-submit']) ) 
        {
        
                $options['title'] = trim(strip_tags(stripslashes($_POST['ace-recent-posts-title'])));
                $options['number'] = (int) $_POST['ace-recent-posts-number'];
                
                if ($options['number'] > 15) $options['number'] = 15;//The limit
    
              update_option('ace_widget_recent_posts', $options);
         }    
    
            $title = attribute_escape( $options['title'] );
            $number = (int) $options['number'];
    
    
    ?>
                <p>
                    <label for="recent-posts-title">
                        <?php _e( 'Title:' ); ?>
                        <input class="widefat" id="recent-posts-title" name="ace-recent-posts-title" type="text" value="<?php echo $title; ?>" />
                    </label>
                </p>
    
                <p>
                    <label for="recent-posts-number"><?php _e('Number of posts to show:'); ?> <input style="width: 25px; text-align: center;" id="recent-posts-number" name="ace-recent-posts-number" type="text" value="<?php echo $number; ?>" />
                    </label>
                    <br />
                    <small><?php _e('(at most 15)'); ?></small>
                </p>
    
                <input type="hidden" name="ace-recent-posts-submit" value="1" />
    
    <?php
      }
    
      function display($args) 
      {
        global $wpdb, $wp_query, $ace_targets;
        // $args is an array of strings that help widgets to conform to
        // the active theme: before_widget, before_title, after_widget,
        // and after_title are the array keys. Default tags: li and h2.
        extract($args);
    
        $options = get_option('ace_widget_recent_posts');
          
        if ( !is_array($options) )
          $options = array('title'=>'',
                   'number' => $this->number );
    
      $cats_to_exclude = '';
    
    
        $title = empty($options['title']) ? __('Recent Posts') : apply_filters('widget_title', $options['title']);
        $number = $options['number'];
    
    /* Here comes ACE patch ;) */
    
        switch(get_option('ace_settings_exclude_method'))
        {
          case "smart":
          
            $cats_to_exclude = get_option("ace_categories_is_home");  
    
            if ($wp_query->is_single)
            {
              $cats = split(',',$cats_to_exclude);
              
              /**
               * If this is a single post, and the 
               */
              $c = count($cats);
              for($i=0;$i<$c;$i++)
              {
                /**
                 * If the post is in one category that has been selected for exclusion 
                 */             
                if(in_category($cats[$i])) 
                {
                  unset($cats[$i]);
                }
              }
              $cats_to_exclude = join(",",(array) $cats);
            }
            elseif ($wp_query->is_category)
            {
              $cats = split(',',$cats_to_exclude);
              
              $c = count($cats);
              for($i=0;$i<$c;$i++)
              {
              /**
               * If this category is beeing listed 
               */          
                if($cats[$i] == $wp_query->query_vars['cat']) 
                {
                  unset($cats[$i]);
                }
              }
              $cats_to_exclude = join(",",(array) $cats);
              unset($cats);
            }
            else
            {
              /**
               * The same as in normal mode. Keep in sync
               */                     
                foreach ($ace_targets as $key=>$val) 
                {
                   if ($wp_query->$key == 1) $filter = $key;        
                }
                
                /**
                 * If this is empty is_home exclusion is in affect
                 */                       
                if (!empty($filter) && $filter != "")
              { 
                $cats_to_exclude = get_option("ace_categories_".$filter);
              }
                
            }        
            
          break;
          
          case "front":
            $cats_to_exclude = get_option("ace_categories_is_home");      
          break; 
    
          case "none":
            $cats_to_exclude = "";
          break;
          
          default:
          case "normal":
          
              foreach ($ace_targets as $key=>$val) 
              {
                 if ($wp_query->$key == 1) $filter = $key;        
              } 
            $cats_to_exclude = get_option("ace_categories_".$filter);
                  
          break;
          }
      
      /**
       * If we got categories to exclude, we want negative values of them
       * because WP_Query requires negative values, in a comma separeted list
       * to the 'cat' value.      
       */     
      if (!empty($cats_to_exclude))
      {
        $cats = array();
        foreach(explode(',',$cats_to_exclude) as $category )
        {
          $cats[]=0-$category;
        }
        
        /**
         * Yes, we overwrite here.
         */         
        $cats_to_exclude = implode(",",$cats);
      }
    
        /**
         * Suppress filters is IMPORTANT
         * 
         * This widget now is better than the original. 
         * Not joking ;)          
         */         
        $r = new WP_Query(array('showposts' => $number, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish','cat'=>$cats_to_exclude, 'suppress_filters'=>1));
          
          if ($r->have_posts()) :
      ?>
    
              <?php echo $before_widget; ?>
                  <?php echo $before_title . $title . $after_title; ?>
                  <ul>
                  <?php  while ($r->have_posts()) : $r->the_post(); ?>
                  <li><a href="<?php the_permalink() ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?> </a></li>
                  <?php endwhile; ?>
                  </ul>
              <?php echo $after_widget; ?>
      <?php
              wp_reset_query();  // Restore global post data stomped by the_post().
          endif;
        }
    }
    
    add_action('widgets_init', array('AceRecentPostsWidget','init'));
    
    ?>
    
    Code (markup):
    Any help is very appreciated! Thanks
     
    m0nk3y, Jan 16, 2011 IP
  2. Nick_Browne

    Nick_Browne Peon

    Messages:
    86
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I don't think u still need to edit the code. Just remove the specific page as a Sticky Page. Or u can also check the sticky page menu itself to re-order the post u want to be highlighted. :)
     
    Nick_Browne, Jan 16, 2011 IP
  3. bob25

    bob25 Well-Known Member

    Messages:
    1,519
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    128
    #3
    Don't the the sticky posts eventually scroll off the recent posts widget? Try scheduling the posts so that it publishes several weeks earlier rather then posting immediately or post dating it.
     
    bob25, Jan 16, 2011 IP
  4. m0nk3y

    m0nk3y Active Member

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Unfortunately I need the Sticky feature for posts to show in a specific area on my homepage, this is due to the way the theme is built.

    The posts will eventually clear off the Recent Posts like, but as I am using this as a brochure site with very, very few updates (perhaps one every year), it may take several months, if not years, for the sticky posts to clear off the list. There are no other posts which I can change the dates for to remove these posts.

    I think editing the code to exclude sticky posts is the only way forward...
     
    m0nk3y, Jan 16, 2011 IP
  5. Dodger

    Dodger Peon

    Messages:
    1,494
    Likes Received:
    60
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Look for the WP_Query call down toward the bottom:

        /**
         * Suppress filters is IMPORTANT
         * 
         * This widget now is better than the original. 
         * Not joking ;)          
         */         
        $r = new WP_Query(array('showposts' => $number, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish','cat'=>$cats_to_exclude, 'suppress_filters'=>1));
    
    Code (markup):
    Add a parameter to exclude sticky posts from the list:

           
        $r = new WP_Query(array('ignore_sticky_posts'=>1, 'showposts' => $number, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish','cat'=>$cats_to_exclude, 'suppress_filters'=>1));
    
    Code (markup):
    You may want to suggest adding the option to the widget. If he does not, any future updates will overwrite your revision to it.
     
    Dodger, Jan 16, 2011 IP
  6. m0nk3y

    m0nk3y Active Member

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    60
    #6
    OK, I have suggested your findings to the plugin developer, however, sticky posts are still being displayed in recent posts. I cannot fathom why this is not working. I am definitely using this plugin (and not the residual Wordpress version) for recent posts in my footer. As soon as I make these posts un-sticky, they are not shown in 'recent posts' as the category they are in has been Excluded (ie. Hidden) courtesy of Advanced Category Excluder plugin.
     
    m0nk3y, Jan 16, 2011 IP
  7. m0nk3y

    m0nk3y Active Member

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    60
    #7
    I believe I have cracked the problem. I don't know how, and leading from your previous post with the code changes, I searched around for articles on limiting recent posts by category, tried limiting it to one single category ID, which none of these Sticky posts are in...and hey presto, only posts from the single defined categoryID are shown in Recent Posts and all other functionality works great.

    So, building on from that. I wondered how I could use the 'exclude category' function and basic category-post exclusion codes I found and bashed this together, works perfectly:

    
    $r = new WP_Query(array('ignore_sticky_posts'=>1, 'showposts' => $number, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish','cat'=>$cats_to_exclude&&cat, 'suppress_filters'=>1));     
    
    Code (markup):
    The above didn't work as you posted, however, added the slight modication of &&cat seemed to do the trick - I have no idea why, as this, surely, would redefine what is calling for an argument (ie. the 'cat' variable is calling on itself).

    Anyhow, it works. Sticky posts are not shown forever in Recent Posts for Advanced Category Excluder Recent Comments Widget and I am one happy bunny!
     
    m0nk3y, Jan 16, 2011 IP
  8. Dodger

    Dodger Peon

    Messages:
    1,494
    Likes Received:
    60
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Kewl. And that is strange the way that functions. It is probably some obscure little thing we are overlooking too.

    You said you mentioned adding the option to the author. Did he answer back?
     
    Dodger, Jan 16, 2011 IP
  9. m0nk3y

    m0nk3y Active Member

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    60
    #9
    I haven't had a reply from the author yet, but I noticed while going through the sites pages/posts that, for some extremely bizarre reason, the Recent Posts shows Sticky posts but ONLY on one single page (which doesn't use the normal page.php for its functionality, but has its own 'portfolio.php', which I have shown below. I cannot understand how the Recent Posts behaves like I want on the homepage, post page, other pages and category pages but not this particular page which I have selected to use a different layout (hence portfolio.php):

    
    <?php get_header(); 
    
    	// Get options for portfolio page ($portfolioID set in checkPageType() found in addon-functions.php)
    	//--------------------------------------------------------------------------------------------------------------
    	
    	$options = get_theme_var('portfolioSettings');	// retrieves settings array from database
    
    	// get portfolio id
    	$flipped_ids = array_flip(get_theme_var('portfolioPages'));
    	$portfolioID = $flipped_ids[$post->ID];
    	
    	$pageID = $post->ID;
    	$pageTitle = get_the_title($post->ID);
    	$useCategories = $options[$portfolioID.'_Categories'];
    	$pageItems = $options[$portfolioID.'_Items'];
    	$linkOption = $options[$portfolioID.'_Open'];
    	
    	// breadcrumbs
    	$hideBreadcrumbs = false;
    	if ( get_post_meta($post->ID, 'breadcrumbOff', true) ) {
    		$hideBreadcrumbs = true;
    	} elseif ( $GLOBALS['globalBreadcrumbsOff'] ) {
    		$hideBreadcrumbs = true;
    	}
    
    	// sub-title
    	$subTitle = get_post_meta($post->ID, 'subTitle', true); // from page options (overrides portfolio setup sub-title)
    	if ( $subTitle == '' ) {
    		$subTitle = $options[$portfolioID.'_SubTitle']; // from portfolio setup
    	}
    	// setup subtitle formatting
    	if ( $subTitle != '' ) {
    		$subTitle = ' &nbsp;//&nbsp; ' . $subTitle;
    	}
    	
    	?>
    
    			<!-- Portfolio/Gallery Content -->
    			<div class="contentArea">
    				<!-- Title / Page Headline -->
    				<div class="full-page">
    					<h1 class="headline"><strong><?php echo $pageTitle; ?></strong><?php echo $subTitle; ?></h1>
    				</div>
    				
    				<div class="hr"></div>
    
    				<?php if (!$hideBreadcrumbs) : ?>
    					<!-- Breadcrumbs -->
    					<div class="full-page">
    						<p class="breadcrumbs"><?php show_breadcrumbs(); ?></p>
    					</div>
    					
    					<!-- End of Content -->
    					<div class="clear"></div>
    				<?php endif; ?>
    			</div>
    			
    			<?php 
    			
    			// Featured Content 
    			if ( $options[$portfolioID.'_Featured'] != '') {
    			
    			?>
    			<!-- Featured Items -->
    			<div class="contentArea" <?php if ($hideBreadcrumbs) { echo 'style="margin-top: -25px;"'; } ?>>
    				<div class="full-page">
    					<?php 
    					query_posts('cat='.$options[$portfolioID.'_Featured'].'&posts_per_page=5');
    					
    					if (have_posts()) : 
    					
    					$loops = 0;
    					while (have_posts()) : the_post(); 
    					
    						$loops++;
    						
    						// get the post image
    						$primaryMedia = get_post_meta($post->ID, "_imageOriginal", true);
    						$portfolioImg = showImage(150, 100, get_the_title(), 'medium');
    						
    						// check for video
    						if ( $portfolioImg['hasvideo'] ) {
    							$is_video = true;	// this isn't an image, so it must be a video
    							$rel = '';
    						} else {
    							// ok, it's an image
    							$fullsizeImg = showImage(640, 480, '', 'original');
    							$is_video = false;
    							$rel = 'rel="featured"';
    						}
    						
    						// image link and class info
    						$imgClass = 'img';
    						if ($linkOption == 'post') {
    							$linkHref = get_permalink();
    							$class = 'class="'. $imgClass .'"';
    						} else {
    							$class = 'class="zoom '. $imgClass .'"';
    							if ($is_video) {
    								$linkHref = $primaryMedia;
    							}else {
    								$linkHref = $fullsizeImg['src'];
    							}
    						}
    
    						// last loop (to alter styles)
    						$style = 'style="margin-right: 17px;"';
    						if ($loops == 5) {
    							$style = 'style="margin-right: 0;"';
    						}
    						
    						?>
    						<a href="<?php echo $linkHref; ?>" <?php echo $class; ?> title="<?php the_title(); ?>" <?php echo $style; ?>  <?php echo $rel; ?>>
    							<?php echo $portfolioImg['full']; ?>
    						</a>
    						<?php
    						
    					endwhile;
    					endif;
    					?>
    				</div>
    				
    				<!-- End of Content -->
    				<div class="clear"></div>
    
    			</div>
    			<?php
    			} // end Featured
    			?>
    
    		
    
    			
    		<?php 
    		query_posts('page_id='.$pageID);
    		
    		if (have_posts()) : 
    		while (have_posts()) : the_post(); 
    			if (get_the_excerpt() != '') {
    			
    				if ($options[$portfolioID.'_Featured'] != '') {
    				// Top page background gap only necessary when using Featured images
    				?>
    				<!-- BEGIN: Floating content area -->	
    				</div>
    				<div class="pageBottom"></div>
    				<div class="pageTop"></div>
    				<div class="pageMain">
    					<div class="contentArea">
    				<?php 
    				}else { 
    					// We're adding the contentArea DIV above so we can have this else condition to do some special styling
    					// when breadcrumbs are off. This way we don't need to test again if featured items are enabled.
    					?>
    					<div class="contentArea" <?php if ($hideBreadcrumbs) { echo 'style="margin-top: -25px;"'; } ?>>
    				<?php } ?>
    				
    						<div class="full-page">
    								<?php
    								// Print content from the page
    								the_content(__('More Information',THEMENAME ).'...');
    								?>
    						</div>
    						
    						<!-- End of Content -->
    						<div class="clear"></div>
    		
    					</div>
    				
    				</div>
    				<div class="pageBottom"></div>
    				<div class="pageTop"></div>
    				<div class="pageMain">
    				<!-- END: Floating content area -->
    				<?php
    			}
    		endwhile;
    		endif;
    		?>
    		
    
    		<div class="contentArea">
    			<div class="full-page">
    				
    				<!-- Gallery/Portfolio -->
    				<div class="portfolio">
    					
    					<?php 
    					
    					// Main gallery/portfolio items
    					
    					// Categories to include
    					if ( is_array($useCategories) ) {
    						$portfolioCategories = implode(',',$useCategories );
    					}
    					
    					// Posts per page
    					$itemsPerPage = ($pageItems <= 0) ? '9' : $pageItems;
    					
    					// query the selected items
    					query_posts('cat='.$portfolioCategories.'&posts_per_page='.$itemsPerPage.'&paged='.$paged);
    					
    					if (have_posts()) : 
    					while (have_posts()) : the_post(); 
    						
    						// get the post image
    						$primaryMedia = get_post_meta($post->ID, "_imageOriginal", true);
    						$portfolioImg = showImage(261, 174, get_the_title(), 'medium');
    						
    						// check for video
    						if ( $portfolioImg['hasvideo'] ) {
    							$is_video = true;	// this isn't an image, so it must be a video
    							$rel = '';
    						} else {
    							// ok, it's an image
    							$fullsizeImg = showImage(640, 480, '', 'original');
    							$is_video = false;
    							$rel = 'rel="portfolio"';
    						}
    						
    						// image link and class info
    						$imgClass = 'img';
    						if ($linkOption == 'post') {
    							$linkHref = get_permalink();
    							$class = 'class="'. $imgClass .'"';
    						} else {
    							$class = 'class="zoom '. $imgClass .'"';
    							if ($is_video) {
    								$linkHref = $primaryMedia;
    							}else {
    								$linkHref = $fullsizeImg['src'];
    							}
    						}
    
    						?>
    						<div class="portfolio-item">
    							<a href="<?php echo $linkHref; ?>" <?php echo $class; ?> title="<?php the_title(); ?>"  <?php echo $rel; ?>>
    								<!--img src="<?php echo $postImage; ?>" width="261" height="174" class="portfolio-image" alt="image" /-->
    								<?php echo $portfolioImg['full']; ?>
    							</a>
    							<div class="portfolio-description">
    								<h4><?php the_title(); ?></h4>
    								<p><?php the_content_rss('...', TRUE, '', 15); ?></p>
    								<!---<a href="<?php echo get_permalink(); ?>"><?php _e('More Information',THEMENAME ) ?>... </a>--->
    							</div>
    						</div>
    						<?php
    						
    					endwhile;
    					endif;
    					?>						
    				</div>
    				
    				<!-- End of Content -->
    				<div class="clear"></div>
    
    				<?php get_pagination(); ?>
    				
    			</div>
    			
    			<!-- End of Content -->
    			<div class="clear"></div>
    		
    		</div>
    <?php get_footer(); ?>
    Code (markup):
    I could do with going to the pub :mad::cool:
     
    m0nk3y, Jan 17, 2011 IP