0

I'm optimizing a WordPress site. For this, I have created a function that remove the old sticky posts. This function doesn't work correctly in some cases. Sometimes all sticky's are removed (so no sticky is set). Is there anyone who could see what this causes?

add_action( 'publish_post', 'wf_clean_sticky', 10, 2);
function wf_clean_sticky($post_id, $post)
{
    //disable function on autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    {
        return;
    }

    // check if current post is sticky
    if(isset($_POST['sticky']) && ($_POST['sticky'] == 'sticky'))
    {
        $array = array($post_id);
        update_option('sticky_posts', $array);
        unset($_POST['sticky']);
    }
}

I've already tried to hook on another functions (e.g. save_post and edit_post) and create a log function for debugging that stores the $_POST to see if there is anything wrong, but I don't get it..

0

Don't unset( $_POST['sticky'] );, leave it be. Otherwise edit_post() will "unstick" your post right after you've just "stuck" it ;)

0

I know it's a little evil to post a plugin as a solution, but the brand new There Can Only Be One plugin seems to do exactly what you want.

The solution it uses (this is pretty much the entire plugin):

add_action( 'draft_to_publish', 'only_one_sticky' );
add_action( 'future_to_publish', 'only_one_sticky' );
add_action( 'new_to_publish', 'only_one_sticky' );
add_action( 'pending_to_publish', 'only_one_sticky' );
add_action( 'publish_to_publish', 'only_one_sticky' );

function only_one_sticky( $post_id ) {
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( ! wp_is_post_revision( $post_id ) ) {
        $post_id = $post_id->ID;
    }
    $sticky = ( isset( $_POST['sticky'] ) && $_POST['sticky'] == 'sticky' ) || is_sticky( $post_id );
    if( $sticky ) {
        $sticky_posts = array();
        $sticky_posts_list = get_option( 'sticky_posts', array() );

        // The Post IDs are stored in the options table as a single list, so we need to construct a new list with the future posts, plus the newly-published sticky post.
        $new_sticky_posts_list = array();
        foreach ($sticky_posts_list as $sticky_post) {
            $postStatus =  get_post_status ( $sticky_post );
            if ( get_post_status ( $sticky_post ) != 'publish' || $sticky_post == $post_id ) {
                array_push( $new_sticky_posts_list, $sticky_post );
            }
        }
        update_option( 'sticky_posts', $new_sticky_posts_list );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.