Skip to content

Instantly share code, notes, and snippets.

@matthewpizza
Last active August 29, 2015 14:01
Show Gist options
  • Save matthewpizza/3855fa6cfd1f86fa75c4 to your computer and use it in GitHub Desktop.
Save matthewpizza/3855fa6cfd1f86fa75c4 to your computer and use it in GitHub Desktop.
Adding Archive Pages to WordPress Menus https://matthewspencer.me/notes/archive-pages-in-menus
<?php
/**
* Register Archive Pages Taxonomy
*/
add_action( 'init', function () {
register_taxonomy( 'archive_pages', 'nav_menu_item', array(
'labels' => array(
'name' => 'Archive Pages',
'singular_name' => 'Archive Page',
),
'show_ui' => false,
'show_in_nav_menus' => true,
'query_var' => false,
'rewrite' => false,
) );
} );
<?php
/**
* Create Archive Pages Terms
*/
add_action( 'init', function () {
static $terms_created = false;
if ( ! $terms_created ) {
$post_types = get_post_types( array(
'publicly_queryable' => true,
'_builtin' => false,
), 'objects' );
$taxonomy = 'archive_pages';
foreach ( $post_types as $term_name => $term ) {
if ( term_exists( $term_name, $taxonomy ) ) {
continue;
}
wp_insert_term( $term->label, $taxonomy, array( 'slug' => $term_name ) );
}
$terms_created = true;
}
} );
<?php
/**
* Add the current menu item class for post type archives.
*
* @param array $classes
* @param object $item
* @return array $classes
*/
add_filter( 'nav_menu_css_class', function ( $classes, $item ) {
$taxonomy = 'archive_pages';
if ( $taxonomy !== $item->object ) {
return $classes;
}
$term = get_term( $item->object_id, $taxonomy );
$post_type = $term->slug;
if ( is_singular( $post_type ) ) {
$classes[] = 'current-menu-parent';
}
else if ( is_post_type_archive( $post_type ) ) {
$classes[] = 'current-menu-item';
}
return $classes;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment