Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpadhariya/fcd1c3758d7bbf0fc26ee52959d73e42 to your computer and use it in GitHub Desktop.
Save vpadhariya/fcd1c3758d7bbf0fc26ee52959d73e42 to your computer and use it in GitHub Desktop.
WordPress - Get posts base on ratio percentage per category
<?php
/**
* Category Ratio: Get Posts base on Custom % per category it means that each category.
*
* Get Category ratio from Settings like below.
* $category_ratio = array(category_id for selected category => inserted category ratio);
*
* NOTE: Most important the total of category ratio for all the selected categories must be 100%
* (this you need to set using JavaScript logic on back admin) otherwise it will create problem.
*/
# Example 1
# Category A 20%
# Category B 20%
# Category C 60%
//$category_ratio = array(41 => 20, 43 => 20, 38 => 60);
# Example 2
# Category A 20%
# Category B 20%
# Category C 35%
# Category D 25%
$category_ratio = array(41 => 20, 43 => 20, 38 => 35, 39 => 25);
// Now base on the categories selected calculate total posts found
$posts = get_posts(array('posts_per_page' => -1, 'category' => array_keys($category_ratio)));
$total_rows_found = count($posts);
/*
* Base on category ratio and found total post we need to find how many posts for each selected category above will come?
*/
$foreach_category_count = [];
foreach($category_ratio as $category_id => $ratio)
{
// Get category count base on their ratio
$foreach_category_count[$category_id] = round($ratio * $total_rows_found/ 100, 0, PHP_ROUND_HALF_DOWN);
}
// Logic summery
print_r($category_ratio);
echo 'Total rows found : ' . $total_rows_found . "\n";
print_r($foreach_category_count);
/**
* Since we have count for each category base on their ratio,
* We now get posts for each category_id and count we calculate above and
* Set all post in a Single Array.
*/
$posts = [];
foreach($foreach_category_count as $category_id => $count)
{
// Get posts base on category_id and their count we calculated.
$get_posts = get_posts(array('posts_per_page' => $count, 'category' => $category_id));
// Merge all the found posts in a single array.
$posts = array_merge($posts, $get_posts);
}
// Print posts summary
print_r($posts);
# Now you can apply your business logic to display images for the posts found here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment