5

EDIT: It is currently working when I set a sticky post and set it's date at 07/07/2016. My code so far: I've added this to change the post date of the post when it become sticky :

//        Update post timestamp
$newdate = current_time('mysql');
        $my_post = array(
            'ID' => $post_id,
            'post_date' => $newdate
        );
        wp_update_post($my_post);
//        Update post timestamp

And also this to unstick the post if it is sticky and older than 7 days :

function deleteOldStickies($post_id, $postDate) {
    $postDate = strtotime($postDate);
    $currentTime = strtotime(time());
    $expire = $currentTime + strtotime('-1 day');
    if ($postDate < $expire && is_sticky()) {
        unstick_post($post_id);
        echo 'Обявата е изтекла!';
    }
}

In content.php I call the function as :

<?php echo deleteOldStickies($post->ID, $post->post_date); ?>

My further question from the info above is - am I missing something important, will it work good in live enviroment?

  • 4
    Not valid enough for a answer, but in this plugin you find all relevant information to use cron and the right hooks to create a solution. – bueltge Jul 8 '16 at 11:39
  • Hi @bueltge , thanks for your answer, can you check my updated question, please? :) – knif3r Jul 8 '16 at 12:53
3

OK I got it working this is the code I used, I am not sure if it is the best practice but it certainly works.

In functions.php where I make the posts sticky from the front-end I added this to update the post_date to today so I can have control over the sticky period:

$newdate = current_time('mysql');
$my_post = array(
    'ID' => $post_id,
    'post_date' => $newdate
);
wp_update_post($my_post);

In functions.php (I used -1 day for testing purpose, if you type -7 days on the $expire variable it will unstick stickyposts older than 7 days.

//Delete Old Stickies START
function deleteOldStickies($post_id, $postDate) {
    $postDate = strtotime($postDate);
    $expire = strtotime('-1 day') + get_option( 'gmt_offset' ) * 3600;
    if ($postDate < $expire && is_sticky()) {
        unstick_post($post_id);
    }
}

//Delete Old Stickies END

In the loop :

<?php echo deleteOldStickies($post->ID, $post->post_date); ?>

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.