Skip to content

Instantly share code, notes, and snippets.

@stracker-phil
Last active April 8, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stracker-phil/55eb6b7c0bf70561fbe2e513fb3b0da7 to your computer and use it in GitHub Desktop.
Save stracker-phil/55eb6b7c0bf70561fbe2e513fb3b0da7 to your computer and use it in GitHub Desktop.
This filter removes all unpublished posts and pages from WordPress menus.
<?php
add_filter( 'wp_nav_menu_objects', 'pst_nav_menu_objects', 10, 2 );
/**
* Modify the WordPress menu and remove entries that are not visible for the current
* user. This applies to all menus (primary, footer, widget ...)
*/
function pst_nav_menu_objects( $items, $args ) {
// If you do not want to modify ALL menus, you can check for the menu-location
// or other criteria here.
// For example, uncomment following condition to only modify the primary menu:
# if ( 'primary' !== $args->theme_location ) {
# return $items;
# }
foreach ( $items as $key => $item ) {
if ( ! in_array( $item->object, array( 'post', 'page' ) ) ) {
// We only check visibility state for posts and pages.
continue;
}
$post_status = get_post_status( $item->object_id );
if ( 'publish' === $post_status ) {
// This is a public page or post. No other check is needed.
continue;
}
if ( is_user_logged_in() ) {
if ( 'protected' === $post_status ) {
if ( current_user_can( 'edit_post', $item->object_id ) ) {
// The current user is the author of the password protected post.
continue;
}
} else {
if ( current_user_can( 'read_post', $item->object_id ) ) {
// The current user can read the draft or trashed post.
continue;
}
}
}
// All positive conditions failed.
// Current visitor has no permission to see this menu entry.
unset( $items[ $key ] );
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment