I want to have a link in the wordpress menu pointing to the latest post of a specific category.
Because I am not able put a dynamic URL in the wordpress menu, my approach was to put a page with a custom page template in the menu.
This page template should behave like the themes single.php
but showing that last post from the given category.
Is there a way to include the themes single.php
and simulate a request of a specific post?
I tried to copy the content of single.php
in a page template and modify the query with
query_posts( array( 'cat' => 9993, 'showposts' => 1) );
If I do that before the_header()
, then I will get no posts. If I do it after the_header()
, then I get the correct content but the header of the theme will set some specific classes for styling a page. So I need the the_header()
function to think the desired post was requested and not the page.
Update:
I did not completely use the solution by toscho because I did not get the active menu entry highlighted and in the right position with that. But he pointed me in the right direction with the wp_nav_menu_objects
filter.
I had a main-menu item CategoryX which should open directly the latest post from CategoryX, and also opening a sub-menu with links to older posts and other related things. The sub-menu should have also a link to the latest Post (LatestFromX) in it, which should also be highlighted directly after klicking on CategoryX in the main menu.
What I basically did was: Creating dummy menu items with the WP admin backend and then replacing its URL with the filter function.
function wp_menu_add_last_from_category_x( $sorted_menu_items, $args ) {
global $wp;
// get url of latest article in CategoryX (CategoryX has id 9993):
$latest = get_posts( array( 'numberposts' => 1, 'category' => 9993 ) );
$latest_url = get_permalink($latest[0]->ID);
// search for the dummy menu items and replace the url:
foreach ($sorted_menu_items as $key => $item) {
if ($item->title === 'CategoryX' || $item->title === 'LatestFromX') {
$sorted_menu_items[$key]->url = $latest_url;
if ($wp->request == $latest[0]->post_name) {
$sorted_menu_items[$key]->classes[] = "current-menu-item";
}
}
}
return $sorted_menu_items;
}