Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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