Search code examples
wordpresssticky

Remove wordpress sticky posts from loop


Not sure if this is the best way to handle this, but I had a need to remove stick posts from the loop, I still need the sticky to show up on the first page, but since I use an endless list I didn't want it showing up twice. This works, but it feels a bit hackish to edit the index.php file to accomplish it... any other thoughts?

//Get the current page number
$url_args=explode('/',trim($_SERVER['REQUEST_URI'],'/'));
$page_number=array_pop($url_args);

$sticky=get_option('sticky_posts');

//if no page number, we are on the home page, so stickies are ok
$print_it=($page_number=='')?true:(in_array(get_the_ID()*1,$sticky)?false:true);

an easier to read if statement:

if($page_number=='' || !in_array(get_the_ID(),$sticky)) $print_it=true;
else $print_it=false;

Solution

  • Firstly, I would use $page_number = (get_query_var('paged')) ? get_query_var('paged') : 1 to establish the current page.

    I am a little confused about your nested if statements (not the easiest to read!!) but I think this function is a little easier to read and maintain:

    $print_it=print_it();
    
    function print_it(){
     if($page_number<=1){
       if (!in_array(get_the_ID(),$sticky){
        return true;
       }
     return false;
     }
    }