0

I have a header and a footer menu (they're the same: Primary Menu). When I'm on a page, wordpress adds classes like current_page_menu. But on pages where I use the query_posts() function the menus after this function dont have those classes added like current_page_menu etc.

Here is my code that is causing the bug:

<?php
  $title_slug = strtolower(str_replace( " ", "-" , the_title_attribute('echo=0') ) );
  $id_obj = get_category_by_slug($title_slug);
  $cat_id = $id_obj->term_id;
  query_posts( 'cat='.$cat_id.'&post_status=publish,future&paged='.get_query_var('paged') );
?>

This code is very useful, though. As it ensures to create a category page by adding a page and selecting the category page template instead of just a link to that category. I had to do this because my category pages need to have child pages.

I'd be greatful if anyone knows a solution!

1 Answer 1

1

The issue is caused by the query_posts function, this function alters the global $wp_query which the menu walker uses to check and add classes like current_page_menu to menu items.

A solution would be to write a new custom query and loop through that than using query_posts.

$title_slug = strtolower(str_replace( " ", "-" , the_title_attribute('echo=0') ) );
$id_obj     = get_category_by_slug($title_slug);
$cat_id     = $id_obj->term_id;
$args       = 'cat='.$cat_id.'&post_status=publish,future&paged='.get_query_var('paged');
// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            //YOUR CONTENT
    <?php endwhile; ?>
        /* Restore original Post Data */
    <?php wp_reset_postdata(); ?>
<?php endif; ?>

References:

2
  • Thank you very much! I didn't know the walker function for the menu classes was using the global query object. Thanks! Feb 10, 2017 at 12:56
  • Maybe you're able to answer this question I asked the community as well Feb 10, 2017 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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