Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PiotrKrzyzek/f8afb17e89471bbaea6f7b450c3acdf0 to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/f8afb17e89471bbaea6f7b450c3acdf0 to your computer and use it in GitHub Desktop.
WordPress - Add Latest Posts (By Category) To Specific Dropdown Menu Item
<?php
function add_latest_post_to_menu_dropdown($items, $menu) {
if( !is_admin() ) {
if ($menu->slug == 'the-menu-slug') {
$post_args = [
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 6,
'category' => 580
];
$order = end($items)->menu_order + 1;
foreach($items as $i){
$classes = [];
foreach($i->classes as $class)
$classes[] = $class;
if ( in_array('show-recents', $classes)) {
$recent_posts = wp_get_recent_posts($post_args);
$reversed_result = array_reverse($recent_posts);
foreach ($reversed_result as $post) {
array_unshift($items, _custom_nav_menu_item($post["post_title"], get_permalink($post['ID']), $order, $i->ID));
$order++;
}
}
}
}
}
return $items;
}
add_filter('wp_get_nav_menu_items', 'add_latest_post_to_menu_dropdown', 10, 2);
function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
if($parent == 0 ) $parent = 0;
$item = new stdClass();
$item->ID = 1000000 + $order + $parent;
$item->db_id = $item->ID;
$item->title = $title;
$item->url = $url;
$item->menu_order = $order;
$item->menu_item_parent = $parent;
$item->type = '';
$item->object = '';
$item->object_id = '';
$item->classes = array();
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->xfn = '';
$item->status = '';
return $item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment