Unstick Sticky Posts Automatically After a Few Days
Removes the sticky flag from posts a set number of days after they were made sticky, so featured announcements do not stay pinned to the top of the blog forever.
Opens WPIDE on
Code
// Days a post stays sticky.
$wpide_sticky_days = 7;
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_unstick_old_posts' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpide_unstick_old_posts' );
}
} );
// Remember when each post became sticky.
add_action( 'post_stuck', function ( $post_id ) {
$since = (array) get_option( 'wpide_sticky_since', array() );
$since[ $post_id ] = time();
update_option( 'wpide_sticky_since', $since, false );
} );
add_action( 'wpide_unstick_old_posts', function () use ( $wpide_sticky_days ) {
$since = (array) get_option( 'wpide_sticky_since', array() );
$sticky = array_map( 'intval', (array) get_option( 'sticky_posts', array() ) );
$changed = false;
foreach ( $sticky as $post_id ) {
if ( ! isset( $since[ $post_id ] ) ) {
$since[ $post_id ] = time();
$changed = true;
} elseif ( $since[ $post_id ] < time() - $wpide_sticky_days * DAY_IN_SECONDS ) {
unstick_post( $post_id );
unset( $since[ $post_id ] );
$changed = true;
}
}
// Forget posts that were unstuck by hand.
foreach ( array_keys( $since ) as $post_id ) {
if ( ! in_array( (int) $post_id, $sticky, true ) ) {
unset( $since[ $post_id ] );
$changed = true;
}
}
if ( $changed ) {
update_option( 'wpide_sticky_since', $since, false );
}
} );
Notes
The countdown starts when the post is made sticky (or when this snippet first sees it); change $wpide_sticky_days.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.