警告:in_array()期望参数2为数组,在给定的情况下为null

I have different headers for different categories within Woocommerce on my website.

I am checking the product category string against an array with the in_array function. Before using the get_template_part function to output the different header to the page.

This code was working fine and has only recently, randomly. Started displaying the PHP error message 'Warning: in_array() expects parameter 2 to be array, null given in'.

    // Gets the product categories to loop over and out put based on scenario below.

    $terms = wp_get_post_terms( $post->ID, 'product_cat' );

    foreach ( $terms as $term ) $categories[] = $term->slug;

    if ( is_front_page() ) {

        get_template_part( '/includes/header/header', 'front' );

    } elseif ( in_array( 'courses', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'single' );

    } elseif ( in_array( 'services', $categories ) ) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'services' );

    } elseif (is_product_category() || is_shop()) {

        get_template_part( '/includes/woocommerce/headers/woocommerce', 'archive' );

    }

    else {  

        get_template_part( '/includes/header/header', 'with-menus' );

    } 

You need to initialize $categories as empty array before foreach runs:

$terms = wp_get_post_terms( $post->ID, 'product_cat' );
$categories = array();

foreach ( $terms as $term ) $categories[] = $term->slug;
[...]

If $terms is empty, you got an empty array $categories and you don't get this error.