1

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

    } 
1
  • 2
    add this in you code $categories=array(); after $terms = wp_get_post_terms( $post->ID, 'product_cat' ); might be a case when $terms is empty array() Commented Apr 1, 2017 at 9:57

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're awesome! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.