amy-d
6/5/2015 - 9:38 PM

PHP: WP - Expanding and collapsing archives

PHP: WP - Expanding and collapsing archives

<ul class="footer__archives">
	<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
	foreach($years as $year) : ?>
			
	<li class="footer__archives__year js-footer__archives__year"><a href="<?php echo get_year_link($year); ?> "><?php echo $year; ?></a></li>

		<?php $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND YEAR(post_date) = '".$year."' ORDER BY post_date DESC");
				
		foreach($months as $month) : ?>
		<li class="footer__archives__month js-footer__archives__month"><a href="<?php echo get_month_link($year, $month); ?>"><?php echo date( 'F', mktime(0, 0, 0, $month) );?></a></li>
		<?php endforeach;?>

	<?php endforeach; ?>
</ul>
	/* handle archives expanding / collapsing within the footer */
	function initFooterArchives() {
		hideArchiveMonths();				// Hide all the archive months to begin with
		
		// Set up archive year click
		$('.js-footer__archives__year').find('a').click(function(e) {
			e.preventDefault();

			var $parent = $(this).parent();

			// If it's expanded, collapse it
			if ($parent.hasClass('expanded')) {
				hideArchiveMonths(); 		// Hide any months that are currently showing
			} 

			// Otherwise, expand it
			else {
				hideArchiveMonths();		// Hide any months that are currently showing

				/* cycle through each item to see if it has a month class and if it's visible */
				var startingPoint = $parent;
				if ( startingPoint.next().is(":visible") ) {
					while (startingPoint.next().hasClass('js-footer__archives__month')) {
						startingPoint.next().fadeOut();
						startingPoint = startingPoint.next();
					}
				} else {
					while (startingPoint.next().hasClass('js-footer__archives__month')) {
						startingPoint.next().fadeIn();
						startingPoint = startingPoint.next();
					}
				}

				$parent.addClass('expanded');
			}
		});

		// initialize it by "clicking" on the first year
		$('.js-footer__archives__year').first().find('a').trigger('click');
	}

	/* hide all the archive month items in the footer
		set all years to closed */
	function hideArchiveMonths() {
		$('.js-footer__archives__year').removeClass('expanded');
		$('.js-footer__archives__month').hide();
	}