Sticky posts in WordPress. How to make them?

81. sticky-posts-2

Sticky Posts is a feature that’s introduced with WordPress Version 2.7. That’s a check box included on the Administration> Posts > Add New Screen. If you check it, the post will be placed at the top of the front page of posts, keeping it there until new posts are published.

Just note that this feature is only available for the built-in post type post and not for custom post types.

Showing Sticky posts

Display just the first sticky post:

$sticky = get_option( ‘sticky_posts’ );

$query = new WP_Query( ‘p=’ . $sticky[0] );

Display just the first sticky post, if none return the last post published:

$args = array(

            ‘posts_per_page’ => 1,

            ‘post__in’  => get_option( ‘sticky_posts’ ),

            ‘ignore_sticky_posts’ => 1

);

$query = new WP_Query( $args );

Display just the first sticky post, if none return nothing:

$sticky = get_option( ‘sticky_posts’ );

$args = array(

            ‘posts_per_page’ => 1,

            ‘post__in’  => $sticky,

            ‘ignore_sticky_posts’ => 1

);

$query = new WP_Query( $args );

if ( isset($sticky[0]) ) {

            // insert here your stuff…

}

Not showing Sticky Posts

Exclude all sticky posts from the query:

$query = new WP_Query( array( ‘post__not_in’ => get_option( ‘sticky_posts’ ) ) );

Exclude sticky posts from a category. Return ALL posts within the category, but don’t show sticky posts at the top. The ‘sticky posts’ will still show in their natural position:

$query = new WP_Query( ‘ignore_sticky_posts=1&posts_per_page=3&cat=6’ );

Exclude sticky posts from a category. Return posts within the category, but exclude sticky posts completely, and adhere to paging rules:

$paged = get_query_var( ‘paged’ ) ? get_query_var( ‘paged’ ) : 1;

$sticky = get_option( ‘sticky_posts’ );

$args = array(

            ‘cat’ => 3,

            ‘ignore_sticky_posts’ => 1,

            ‘post__not_in’ => $sticky,

            ‘paged’ => $paged

);

$query = new WP_Query( $args );

This much guys! Hope you this article was helpful for you!

Share this!

Post Author: Staff

Leave a Reply

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