WordPress.org

Ready to get started?Download WordPress

Forums

Plugin: Scheduling an event to add sticky class on most viewed posts (1 post)

  1. carlodurso
    Member
    Posted 1 year ago #

    I've created a plugin to run a cron every 30 minutes to check if posts have been viewed more than 50 times, if so it will attach the sticky class to each of them.

    As you can see in the code I'm using add_filter but it's not applying the class as expected. I've tested the code by sending test emails and it works fine.

    register_activation_hook(__FILE__, 'my_activation');
    add_action('my_event', 'promote_post');
    
    function my_activation() {
    	if ( !wp_next_scheduled('my_event') ) {
    		wp_schedule_event(time(), 'thirty-mins', 'my_event');
    	}
    }
    
    function promote_post(){
    
    	add_filter('post_class', function ($classes){
    
    	global $post;
    
    	 if (is_home() && wpp_get_views( $post->ID) > 50 ){
    	   stick_post( get_the_ID() );
    	  } else { unstick_post(get_the_ID());
    	  		}
    	return $classes;
    	});
    }
    
    add_filter( 'cron_schedules', function($schedules){
    
    	$schedules['thirty-mins'] = array(
    		'interval' => 1800,
    		'display' => 'Every Thirty Minutes'
    	);
    	return $schedules;
    
    });
    
    register_deactivation_hook(__FILE__, 'my_deactivation');
    
    function my_deactivation() {
    	wp_clear_scheduled_hook('my_event');
    }

Topic Closed

This topic has been closed to new replies.

About this Topic