Hello Ahmed,
To get the most popular posts in each category, start with getting a list of categories.
Then you will get the most popular posts for each category and finally, display them in a list.
1) Get a list of categories
The following will return an array of all the categories:
$arCat = get_categories();
See: https://developer.www.ads-software.com/reference/functions/get_categories/
2) Get the most popular posts for each category.
For this, create a function like below:
function MostPopular($NumPosts, $Category){
//Returns most popular posts.
$query = new WP_Query( array(
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'posts_per_page' => $NumPosts,
'cat' => $Category
) );
wp_reset_postdata();
return $query->posts;
}
See: https://codex.www.ads-software.com/Class_Reference/WP_Query
3) Start building the list:
$arCat = get_categories(); //Get array of all categories
echo '<ul>'; //Start the list
foreach ($arCat As $Category) { // Go through each category
echo '<li>'.$Category->name; // Print the category name
echo '<ul>'; // Start the posts list for each category
$CatID = $Category->term_id;
$arPopular = MostPopular(2, $CatID ); //Get posts for this category. Only shows 2 of them
foreach ($arPopular As $popPost) { //Display posts
echo '<li>'
.'<a href="'.get_permalink($popPost->ID).'">'.$popPost->post_title.'</a>' // Get Permalink for post and display
.'</li>';
}
echo '</ul>';
echo '</li>';
}
echo '</ul>';
See: https://developer.www.ads-software.com/reference/functions/get_categories/
See: https://developer.www.ads-software.com/reference/functions/get_permalink/