Strange side effect of a PHP post query code in WordPress

Riccardo asked
php wordpress menu blogs posts
via

Why this code in functions.php has this strange side effect of switching the menu to the mobile version in not-home pages in wordpress?

function my_blog_category( $query ) {
 if ( $query->is_home() && !is_front_page() || is_archive()) {
 $query->set( 'cat', '6');
 }
}
add_action( 'pre_get_posts', 'my_blog_category' );

This code should affect only posts in blog and archive page so why’s that?


Answer
via

The reason it’s not working is because you were asking:

  • If $query->is_home() && !is_front_page()
  • Or, is_archive()

Group your conditional expression using brackets.

function my_blog_category( $query ) {
    if ( $query->is_home() && ( !is_front_page() || is_archive() ) ) {
        $query->set( 'cat', '6');
    }
}
add_action( 'pre_get_posts', 'my_blog_category' );

Now you’re asking:

  • If $query->is_home()
    • And, if !is_front_page() or is_archive()
Share This
Posted in: