Skip to content

Instantly share code, notes, and snippets.

@Viper007Bond
Created May 8, 2012 20:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Viper007Bond/2638975 to your computer and use it in GitHub Desktop.
Save Viper007Bond/2638975 to your computer and use it in GitHub Desktop.
<?php
/**
* This is a version of
* http://www.viper007bond.com/2011/09/20/code-snippet-add-a-link-to-latest-post-to-wordpress-nav-menu/
* that supports multiple placeholders. In this case, the placeholder fetches
* the latest post from a particular category.
*/
// Front end only, don't hack on the settings page
if ( ! is_admin() ) {
// Hook in early to modify the menu
// This is before the CSS "selected" classes are calculated
add_filter( 'wp_get_nav_menu_items', 'replace_placeholder_nav_menu_item_with_latest_post', 10, 3 );
}
// Replaces a custom URL placeholder with the URL to the latest post
function replace_placeholder_nav_menu_item_with_latest_post( $items, $menu, $args ) {
// Loop through the menu items looking for placeholder(s)
foreach ( $items as $item ) {
$args = array(
'numberposts' => 1,
);
switch ( $item->url ) {
case '#latestpost-category-abc':
$args['category'] = 4;
break;
case '#latestpost-category-some-other-cat':
$args['category'] = 123;
break;
// Not one of our placeholders
default;
continue 2;
}
// Get the latest post
$latestpost = get_posts( $args );
if ( empty( $latestpost ) )
continue;
// Replace the placeholder with the real URL
$item->url = get_permalink( $latestpost[0]->ID );
}
// Return the modified (or maybe unmodified) menu items array
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment