PHP: Wordpress Popular Posts for the current category
Hi folks!
For my work, I luckily had to hack a client Wordpress instance... I'm glad to reached 6 years of studies after my A-Level to finally be a Wordpress hacker.
Anyway, today, my client Wordpress uses the popular plugin Wordpress Popular Posts to display various popular posts on his website. The plugin allows to exclude certain categories if you want but doesn't allow to filter for only one specific category. I read in the plugin forum that the plugin developer has this feature in his to-do list...
If you need this feature by the current version (2.2.1), here is the small « hack » I wrote:
As not a Wordpress developer, I would be thankful if you have any optimization to provide. Just before your dynamic_sidebar()
function call, paste this code to get the popular post for the current category only:
<?php
// Gets the current sidebar widgets
$side_bar_widgets = wp_get_sidebars_widgets();
// Finds the WPP plugin number
foreach ($side_bar_widgets['my-lovely-sidebar-id'] as $widget_name) {
preg_match('/^wpp-(\d)$/', $widget_name, $matches);
if (!empty($matches)) {
$widget_num = intval($matches[1]);
break;
}
}
// Gets all category IDs
$cate_ids = get_all_category_ids();
// Gets the current category ID
$current_cate_id = array_shift(get_the_category())->cat_ID;
// Substracts the current category ID from the category ID array
$current_cate_pos = array_search($current_cate_id, $cate_ids);
unset($cate_ids[$current_cate_pos]);
// Builds the WPP category exclusion array
$exclude_cats = array(
'active' => 'on',
'cats' => implode(',', $cate_ids)
);
// Gets the widget options
$widget_wpp_options = get_option('widget_wpp');
// Sets the category exclusion parameter
$widget_wpp_options[$widget_num]['exclude-cats'] = $exclude_cats;
// Saves the widget options
update_option('widget_wpp', $widget_wpp_options);
// Calls the sidebar
if (!dynamic_sidebar('my-lovely-sidebar-id')) {
// Outputs something probably awesome
}
Do not hesitate to share this little code snipet, I worked f**cking hard to produce it.
See you at next level!