1

Hi I have this code for custom post types

add_filter( 'pre_get_posts', 'my_get_posts' );

 function my_get_posts( $query ) {
if ( is_home() )
    $query->set( 'post_type', array( 'post', 'page', 'album', 'movie', 'quote', 'attachment' ) );

return $query;
}

i added it to my functions.php file, it works but it makes my navigation menu disappear.

2

It looks like you're overwriting the nav menu query. By adding the ! is_admin() and $query->is_main_query() conditionals, you can ensure that you're targeting the main query for posts on the front end.

add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {

 if ( ! is_admin() && $query->is_main_query() && is_home() )
    $query->set( 'post_type', array( 'post', 'page', 'album', 'movie', 'quote', 'attachment' ) );

return $query;
}
| improve this answer | |
1

The reason the query was hiding navigation is because you were missing the 'nav_menu_items' post type:

add_filter( 'pre_get_posts', 'filter_pre' );
function filter_pre( $query ) {
    if( ! $query->is_main_query() || ! $query->is_home() )
        return $query;
    $query->set( 'post_type', array( 'posts', 'custom_p_type', 'nav_menu_items' ) );

    return $query;
 }
| improve this answer | |
1

Found a solution, and it does more than what i asked. This solution shows the custom post types that you want to appear on the homepage and the second half shows it in the archives and search results :)

add_filter( 'pre_get_posts', 'my_get_posts' );

function my_get_posts( $query ) {

    if ( is_home() && false == $query->query_vars['suppress_filters'] || is_feed() )
            $query->set( 'post_type', array( 'posts', 'custom_post_type_name' ) );

    return $query;
 }

 add_filter('pre_get_posts', 'query_post_type');
 function query_post_type($query) {
 if ( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
$post_type = get_query_var('post_type');
    if($post_type)
        $post_type = $post_type;
    else
        $post_type = array('posts', 'custom_post_type_name');
$query->set('post_type',$post_type);
    return $query;
}
}

Place this in your functions.php file

| improve this answer | |

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.