0

I am wanting to add individual posts to my primary menu programatically based on category

I have used the wp_nav_menu_items filter previously to add pages to the menu but I am stuck when it comes to adding posts.

add_filter( 'wp_nav_menu_items', 'fx_user_menu', 10, 2 );

function fx_user_menu( $items, $args ) {
    if ($args->theme_location == 'primary') {
        $myposts = get posts from specified category
            foreach ( $myposts as $post ) {
            $items .= '<li><a href="' . the_permalink() . '">' . the_title() . '</a></li>';
            }
    }   
    return $items;
}

Any ideas on how to get this working?

0

I'm not 100% sure if I get you right, but maybe this will solve your problem:

add_filter( 'wp_nav_menu_items', 'fx_user_menu', 10, 2 );

function fx_user_menu( $items, $args ) {
    if ($args->theme_location == 'primary') {
        $myposts = get_posts( array(
            'category' => <YOUR CATEGORY ID GOES HERE>,
            'posts_per_page' => 5
        ) );

        foreach ( $myposts as $post ) {
            // you should not use the_title and the_permalink outside of The Loop - they won't work correctly
            $items .= '<li><a href="' . get_permalink($post->ID) . '">' . apply_filters('the_title', $post->post_title) . '</a></li>';
        }
    }   
    return $items;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.