RSS_Button

Track all Post views from Single Admin Page



A while back i came across this code snippet that adds post views counts to all post and pages using post metadata. the problem is that when you have a lots of custom post types its a problem to go and check, which are the post with the top views in each post-type.

Hence i made a dedicated admin page where all the top posts for each post type are seperated, for easy viewing and analysis.. below is the code.
Leave me a comment if you have any questions.

	$args=array(
	  'public'   => true,
	  'hierarchical' => true,
	); 
	
	$post_types=get_post_types($args,'names','or'); 
	
	//Run a loop on all available post-types
	foreach ($post_types as $post_type ) {
		
		//Post types you want to ignore.
		if ($post_type == "post" || $post_type == "attachment" ){}
		else{
		
			//Output post-type name for heading.
			echo '<h1>'.$post_type.'</h1>';
			
			$args = array(
				//How many top post should display.
				'posts_per_page' => -1, 
				'post_type' => $post_type,
				'meta_key' => 'post_views_count',
				//Sort by highest post-views.
				'orderby' => 'meta_value_num', 
				'post_status' => 'publish' 
		
			);
			
			$the_query = new WP_Query( $args );
			
			while ( $the_query->have_posts() ) : $the_query->the_post();
			
				echo "<table class='form-table'>";
		
				echo "<tr valign='top'>";
				echo "<td width=400>";
				echo "<label for='blogname'>".the_title()."</label>";
				echo "</td><td>";
				echo get_post_meta(get_the_ID(), 'post_views_count', true);
				echo "</td></tr>";
			
				echo "</table>";
				
			endwhile;
			
			//Reset the query.
			wp_reset_postdata();
			
			}	
		
	}

Most Related Posts

  • No Related Posts Found