• Resolved slaterino

    (@slaterino)


    Hi,
    I’m getting an error with my foreach loop in debug.log, and can’t seem to work out the issue. I’ve looked at the WordPress documentation (https://codex.wordpress.org/Function_Reference/get_post_custom_values) and the code looks completely fine to me. Does anyone know what’s causing the problem? Here’s my error message followed by the code.

    [25-Nov-2015 11:51:05 UTC] PHP Warning: Invalid argument supplied for foreach() in /home/sites/domain.com/public_html/wp-content/themes/maintheme/content-event.php on line 262

    <?php
    		$duplicate_logo_field = get_post_custom_values('como-logos');
    		foreach ( $duplicate_logo_field as $key => $value ) {
    		$slide_attr = array(
    			'class' => "como-logo",
    			'alt'	=> get_post($value)->post_excerpt
    		);
    		echo wp_get_attachment_image($value, 'funder-logo', false, $slide_attr);
    		} ?>

    Thanks,
    Russ

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try checking if get_post_custom_values() returns an array of values or NULL.

    <?php
    // Returns an array or NULL
    $duplicate_logo_field = get_post_custom_values( 'como-logos' );
    
    // Check if it's an array
    if ( is_array( $duplicate_logo_field ) ) {
    	foreach ( $duplicate_logo_field as $key => $value ) {
    		$slide_attr = array(
    			'class' => "como-logo",
    			'alt' => get_post( $value )->post_excerpt
    		);
    		echo wp_get_attachment_image( $value, 'funder-logo', false, $slide_attr );
    	}
    }
    ?>
    Thread Starter slaterino

    (@slaterino)

    Of course! It was so simple. I needed to add an ‘if not empty’ statement before running the loop. That has now been done and the problem is solved. Thanks so much for your help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Invalid argument supplied for foreach()’ is closed to new replies.