Show only sticky posts on home page in WordPress

To create a list of posts by WordPress query it is possible to filter it by adding a custom filter to the condition. For example, if you need to show only sticky posts, you have to take a list of all sticky posts and add optional filter to WHERE condition.

$sticky = get_option('sticky_posts');
$where .= ' AND wp_posts.ID IN ('.implode(',', $sticky).') ';

If such a condition is necessary only for the main page, you have to add a check is_home(). To change the conditions in the query in WordPress there is a special filter posts_where, which returns the current value of the WHERE condition of the database query. This filter can be used to develop plugins, for example to show only sticky content on the main page:

<?php
//Plugin Name: Forever Sticky
//Description: Show only sticky posts on home page
//Author:      Polyetilen
//Version:     1.0

function forever_sticky_condition ( $where ) { 
	if(is_home()){
		$sticky = get_option('sticky_posts');
		if(count($sticky)>0){
			return $where.' AND wp_posts.ID IN ('.implode(',', $sticky).') ';
		}else{
			return $where;
		}
	}else{
		return $where;
	}
}

add_filter('posts_where', 'forever_sticky_condition'); 
?>

Download plugin Forever sticky.

This entry was posted in Programming, WordPress and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.