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

Bre*_*ing 1 php arrays wordpress

我在我的网站上的Woocommerce中有不同类别的不同标题.

我正在使用in_array函数检查数组的产品类别字符串.在使用get_template_part函数向页面输出不同的标头之前.

这段代码工作正常,最近才随机.开始显示PHP错误消息'警告:in_array()期望参数2为数组,在'中给出为null.

    // 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' );

    } 
Run Code Online (Sandbox Code Playgroud)

Jou*_*uby 6

在foreach运行之前,您需要初始化$categories空数组:

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

foreach ( $terms as $term ) $categories[] = $term->slug;
[...]
Run Code Online (Sandbox Code Playgroud)

如果$terms为空,则表示您有一个空数组, $categories并且不会出现此错误.