Sticky Posts In WordPress
As of WordPress version 2.7 you've been able to assign some posts to be sticky, a sticky post will make sure that this post appears at the top of the list of posts.
If you use your WordPress site as a normal blog and have a list of posts of the homepage of your site, making a post sticky will ensure that this post appears at the top of the list.
To make a post sticky all you have to do is click the checkbox on the edit posts screen.
In the visibility dropdown there is a checkbox called Stick this post to the front page, check this box and click update to make the post sticky. Now return to the homepage of your site and you will see this post at the top of the screen.
This updates a option on the wp_options table, this is stored in a meta option under sticky_posts, where it will store a list of all sticky post IDs.
Get All Sticky Posts
As all the sticky posts are stored in the wp_options table we can use the WordPress get_option( 'sticky_posts' ) function to return all the sticky post ID's on your WordPress site.
$sticky = get_option( 'sticky_posts' );
Programmatically Assign Post As Sticky
If for example you are writing a script to do a mass import into WordPress then you would be creating new post items programmatically by using the function wp_insert_post( $post ).
The argument that you pass into this function is all the settings that you can assign to your post such as the title, body, categories etc. But there isn't an argument to make the post sticky from these settings.
To programmatically make a post sticky you need to use another function on the post ID. WordPress comes with a function to do just this job, by using the function stick_post( $id ), you can make any post sticky.
The return of the wp_insert_post() function will be the new post ID that was added to the database, you can now use this value on the sticky_post() function.
$id = wp_insert_post( $postArgs ); stick_post($id);
- Access 100s of premium tutorials and downloadable content
- Members content consists of premium WordPress plugins
- CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
- In-depth development tutorials
- Priority tutorial requests
- No ads
- First month free!