questions

How to fix this “Undefined index: post_type” error?

Rate this post

I am getting this error:

Notice: Undefined index: post_type in /opt/bitnami/apps/wordpress/htdocs/wp-content/themes/porto-child/functions.php on line 225

Line 225 corresponds to switch ( $query->query_vars['post_type'] ) in code below:

// Set Number of Custom Post Type Displayed Per Page

function set_posts_per_page_for_haivision_custom_post_type($query)
{
    switch ( $query->query_vars['post_type'] )
    {
        case 'press_release':  
            $query->query_vars['posts_per_page'] = -1;
            break;

        case 'video_portal':  
            $query->query_vars['posts_per_page'] = -1;
            break;

        default:
            break;
    }
    return $query;
}

if( !is_admin() )
{
    add_filter( 'pre_get_posts', 'set_posts_per_page_for_haivision_custom_post_type' );
}

Can anyone help?

 

✔️Solution:

post_type is not always used in a WP Query, you could wrap your switch statement with an if that checks for its presence:

function set_posts_per_page_for_haivision_custom_post_type($query)
{
    if( isset( $query->query_vars['post_type'] ) )
    {
        switch ( $query->query_vars['post_type'] )
        {
            case 'press_release':  
                $query->query_vars['posts_per_page'] = -1;
                break;

            case 'video_portal':  
                $query->query_vars['posts_per_page'] = -1;
                break;

            default:
                break;
        }
    }

    return $query;
}

but, WP_Query provides 2 methods to access its variables: get and set, the former already checks whether the variable you’re looking for exists, so you don’t have to do it yourself:

function set_posts_per_page_for_haivision_custom_post_type($query)
{
    switch ( $query->get('post_type') )
    {
        case 'press_release':  
            $query->set('posts_per_page', -1);
            break;

        case 'video_portal':  
            $query->set('posts_per_page', -1);
            break;

        default:
            break;
    }
    return $query;
}

Leave a Reply

Your email address will not be published.

Back to top button