WordPress.org

Support

Support » Plugins and Hacks » Hacks » [Resolved] Adding sticky class to most viewed posts

[Resolved] Adding sticky class to most viewed posts

  • I’m trying to write a fucntion in functions.php that promotes a post to featured depending on how many times has been viewed. For the views count I’m using a plugin method (WordPress Popular Posts). The theme is based on Roots.

    function promote_post($promoted) {
    	global $post;
    
    	foreach(($post->ID) as $promoted ){
    		wpp_get_views($post->ID);
    	}
    
      	if (is_home() && (wpp_get_views($post->ID) > 2)){
    	        stick_post($promoted);
    	  }
    	}
    	add_filter('post_class', 'promote_post');

    I’m not able to loop through all the posts and set the sticky class according to the condition. The error I get is: Invalid argument supplied for foreach().

Viewing 2 replies - 1 through 2 (of 2 total)
  • foreach needs an array argument for which it can step through each element. $post->ID is an integer, there are not multiple elements to step through.

    I believe ‘post_class’ fires on each post in the loop, so you can just get the views for the current post and promote as needed. No foreach loop needed.

    Just a suggestion– This seems overkill to check for posts to promote on every page load. You might consider doing this less often as a scheduled task.

    bcworkz you’re right on both, the foreach and the scheduled task. I’ll look into it. Thanks.

    This is the working code for reference:

    function promote_post($classes) {
    	global $post;
    
    	 if (is_home() && wpp_get_views($post->ID) > 10){
    	   stick_post(get_the_ID());
    	  } else {unstick_post(get_the_ID());
    	  		}
    	  return $classes;
    	}
    	add_filter('post_class', 'promote_post');
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[Resolved] Adding sticky class to most viewed posts’ is closed to new replies.