【问题标题】:Warning: in_array() expects parameter 2 to be array, null given in警告:in_array() 期望参数 2 是数组,在
【发布时间】:2017-08-26 14:10:57
【问题描述】:

我在我的网站上的 Woocommerce 中为不同类别设置了不同的标题。

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

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

    } 

【问题讨论】:

  • $terms = wp_get_post_terms( $post->ID, 'product_cat' ); 之后添加这个代码$categories=array(); 可能是$terms 为空数组()的情况

标签: php arrays wordpress


【解决方案1】:

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

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

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

如果$terms 为空,您将得到一个空数组 $categories,您不会收到此错误。

【讨论】:

  • 你太棒了!谢谢!
猜你喜欢
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
相关资源
最近更新 更多