Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.