1

I have created a custom post type. It seems to work fine. I searched the following code to have the custom post types show within the other posts on the blog's front page:

//add custom post type to front page
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )

    return;
        $query->set( 'post_type', array( 'post', 'reviews' ) );

}

However, this one piece of code makes all my menu items disappear on all menus. I only have three menus: the main header menu, a footer menu, and a mobile menu. I do not have a lot of items at all.

When I removed the above code from functions.php, the menu items re-appeared, but now my custom post type doesn't show on the front page.

Does anyone have any ideas why the code would cause the menu items to disappear?

1

Here's a breakdown of what's happening with the code you've posted.

This code is saying, If this is the home page and the main query is being used, don't do anything.

if ( is_home() && $query->is_main_query() )

return;

That's no good! The intention is to modify the query if we're on the homepage and the main query is being run.

Then we have:

$query->set( 'post_type', array( 'post', 'reviews' ) );

This code is correctly setting the query up to get posts of the post types post and reviews, but because of the conditional statement above it, it's going to be firing for non main queries, which is why it's messing up your menus. Navigation menus and secondary loops don't use the main query.

Here's an updated version of your code that will work:

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
    // Bail if this is not the home page or if it's not the main query.
    if ( ! is_home() && ! $query->is_main_query() ) {
        return;
    }

    $query->set( 'post_type', array( 'post', 'reviews' ) );
}

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.