On putukrejums.lv blog we use the ‘sticky’ posts to add introductory information to all category pages (see here, for example). This approach is better than using the category description field because it allows for all the usual formatting options.
Here is how to add sticky posts on top of their respective category index pages and hide them from the rest of pages and indexes:
add_action('pre_get_posts', 'alter_stickies'); function alter_stickies($query) { if (!$query->is_category && !$query->is_single) $query->set('post__not_in', get_option('sticky_posts')); } add_filter('posts_orderby', 'sticky_orderby'); function sticky_orderby($orderby){ global $wpdb; if (is_category()) $orderby = "Field(". $wpdb->prefix ."posts.ID," . implode(',', get_option('sticky_posts')) . ") DESC, " . $orderby; return $orderby; }
Add the is-sticky
class to the post wrap for additional formatting control:
add_filter('post_class', 'add_stickies_class'); function add_stickies_class($classes) { if (is_sticky()) $classes[] = 'is-sticky'; return $classes; }
Redirect Sticky Posts to Their Category Index Page
We don’t want the sticky posts to be available as individual posts that can be access via their permalinks because this information is already being displayed at the top of every category index page. Here is a simple filter to redirect all sticky posts to their category index pages:
add_action('template_redirect', 'redirect_stickies'); function redirect_stickies() { global $wp_query; if (!is_single()) return; $stickies = get_option('sticky_posts'); if (empty($stickies)) return; if (in_array($wp_query->post->ID, $stickies)) if ($cats = get_the_category($wp_query->post->ID)) if ($cat = end($cats)) wp_redirect(get_category_link($cat->cat_ID), '302'); }
As some would say
I’m gonna use this right away :)
This is EXACTLY what I was looking for. Thank you so much for sharing!
What files are you adding this code to? Does this prevent showing sticky posts on the homepage and instead show them as sticky posts on the category pages only?