Search code examples
phpwordpressfunctionmeta

Reset post meta after time in Wordpress


So i have this function for my Wordpress site which basically just counts every click and shows the most popular ones in a loop. My problem is that the meta fields doesn't reset or decrease after time. So it will show old posts instead of new ones. I don't have that much knowlege in PHP so if anyone can help me, that will be greatly appreciated!

This is my current PHP function:

function shapeSpace_popular_posts($post_id) {
    $count_key = 'popular_posts';
    $count = get_post_meta($post_id, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
    } else {
        $count++;
        update_post_meta($post_id, $count_key, $count);
    }
}

add_action('wp_ajax_track_clicks', 'track_clicks');
add_action('wp_ajax_nopriv_track_clicks', 'track_clicks');

function track_clicks(){
    $post_id = $_POST['post_id'];
    shapeSpace_popular_posts($post_id);
    echo 'Success';
    wp_die();
}

Solution

  • Use wp_schedule_event() function to run a function that sets all post meta to 0:

    https://codex.wordpress.org/Function_Reference/wp_schedule_event

    And add a custom recurrence interval :

    function add_cron_recurrence_interval( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 180,
        'display'   => __( 'Every 3 Minutes', 'textdomain' )
        );    
        return $schedules;
    }
    add_filter( 'cron_schedules', 'add_cron_recurrence_interval' );
    

    To delete all post meta, use <?php delete_post_meta_by_key( 'popular_posts' ); ?>

    https://codex.wordpress.org/Function_Reference/delete_post_meta

    Also, i recommend you sanitize

    $_POST['post_id'] 
    

    with

    intval($_POST['post_id'])
    

    https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data