Created
August 24, 2012 10:05
-
-
Save shuhei/3448667 to your computer and use it in GitHub Desktop.
Add 'cat' query to `wp_get_archives()`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Example: | |
// $cat_ID = 12; | |
// wp_get_cat_archives('type=monthly', $cat_ID); | |
// | |
// Borrowed a lot from the following links. | |
// | |
// - http://wordpress.org/support/topic/wp_get_archives-and-conditional-tags | |
// - http://www.stemlegal.com/greenhouse/2012/setting-up-month-archives-to-only-display-custom-taxonomy-wordpress/ | |
// | |
add_filter('getarchives_where', 'custom_archives_where', 10, 2); | |
add_filter('getarchives_join', 'custom_archives_join', 10, 2); | |
function custom_archives_join($x, $r) { | |
global $wpdb; | |
$cat_ID = $r['cat']; | |
if (isset($cat_ID)) { | |
return $x . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)"; | |
} else { | |
return $x; | |
} | |
} | |
function custom_archives_where($x, $r) { | |
global $wpdb; | |
$cat_ID = $r['cat']; | |
if (isset($cat_ID)) { | |
return $x . " AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN ($cat_ID)"; | |
} else { | |
$x; | |
} | |
} | |
function wp_get_cat_archives($opts, $cat) { | |
$args = wp_parse_args($opts, array('echo' => '1')); // default echo is 1. | |
$echo = $args['echo'] != '0'; // remember the original echo flag. | |
$args['echo'] = 0; | |
$args['cat'] = $cat; | |
$archives = wp_get_archives(build_query($args)); | |
$archs = explode('</li>', $archives); | |
$links = array(); | |
foreach ($archs as $archive) { | |
$link = preg_replace("/href='([^']+)'/", "href='$1?cat={$cat}'", $archive); | |
array_push($links, $link); | |
} | |
$result = implode('</li>', $links); | |
if ($echo) { | |
echo $result; | |
} else { | |
return $result; | |
} | |
} |
This is from 10 years ago. I'd be surprised if it works. Many things in the WordPress code base should have changed completely. Please forget about this ancient gist.
This is from 10 years ago. I'd be surprised if it works. Many things in the WordPress code base should have changed completely. Please forget about this ancient gist.
It almost works, could you see why it doesn't work?
No. Sorry. I don't remember anything about this 😅
It's working perfectly on first try, thanks for the 10 year code! -Add the code above to functions.php and then in your sidebar template add
$cat_ID = 12; // Your cat ID
wp_get_cat_archives('type=monthly', $cat_ID);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, why is this not working now? Please tell me how to fix?