提问者:小点点

警告:in_array()要求参数2为array,在


我在我的网站上的Woocommerce内有不同类别的不同标题。

我正在用in_array函数对照一个数组检查产品类别字符串。 然后使用get_template_part函数将不同的头输出到页面。

这段代码运行良好,只是最近才随机出现。 开始显示PHP错误消息“warning: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' );

    } 

共1个答案

匿名用户

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

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

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

如果$terms为空,则得到一个空数组$categories,并且不会得到此错误。