<?php

/**
 * When viewing a single post witnin a category that is assigned to a static
 * page, make sure that the pages get the proper class names.
 */
function acme_filter_list_pages_for_category_static_pages($list){
	//Add classes for when news
	if(is_single() && in_category(ACME_NEWS_CATEGORY_ID)){
		$list = preg_replace('/(?=page-item-' . ACME_ABOUTUS_PAGE_ID . '\b)/', 'current_page_ancestor ', $list);
		$list = preg_replace('/(?=page-item-' . ACME_NEWS_PAGE_ID . '\b)/', 'current_page_ancestor current_page_parent ', $list);
	}
	return $list;
}
add_filter('wp_list_pages', 'acme_filter_list_pages_for_category_static_pages');


/**
 * Make sure posts in a category assigned to a static page appear under it in the
 * URI structure. Requires a permalink structure prefixed by /%category%/...
 */
function acme_rewrite_post_links_for_static_page_categories($permalink, $post, $leavename){
	if(in_category(ACME_NEWS_CATEGORY_ID, $post)){
		return preg_replace("{.+?/(?=\d\d\d\d)}", get_permalink(ACME_NEWS_PAGE_ID), $permalink);
	}
	return $permalink;
}
add_filter('post_link', 'acme_rewrite_post_links_for_static_page_categories', 10, 3);


/**
 * Make it so that when linking to a category, they are linked to the category's
 * associated static page instead.
 */
function acme_rewrite_static_page_category_links($catlink, $category_id){
	if($category_id == ACME_NEWS_CATEGORY_ID)
		return get_permalink(ACME_NEWS_PAGE_ID);
	return $catlink;
}
add_filter('category_link', 'acme_rewrite_static_page_category_links', 10, 2);


/**
 * When attemptint to view category that is assigned to a static page, redirect
 * to the page.
 */
function acme_redirect_to_static_category_page(){
	global $wp_query;
	if(is_category(ACME_NEWS_CATEGORY_ID)){
		wp_redirect(get_permalink(ACME_NEWS_PAGE_ID));
	}
}
add_action('template_redirect', 'acme_redirect_to_static_category_page', 10, 3);


//Not included: rewriting archive pages