Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, string given in

565 views Asked by At

The above error appears in PHP 8.0, pointing to the line of code below:

if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {

Section of code for this function:

function wpsc_product_image( $attachment_id = 0, $width = null, $height = null ) {

// Do some dancing around the image size
if ( ( ( $width >= 10 ) && ( $height >= 10 ) ) && ( ( $width <= 1024 ) && ( $height <= 1024 ) ) ) {
    $intermediate_size = "wpsc-{$width}x{$height}";
}

// Get image url if we have enough info
if ( $attachment_id > 0 && ! empty( $intermediate_size ) ) {

    // Get all the required information about the attachment
    $uploads    = wp_upload_dir();
    $image_meta = get_post_meta( $attachment_id, '' );
    $file_path  = get_attached_file( $attachment_id );

    // Clean up the meta array
    foreach ( $image_meta as $meta_name => $meta_value ) {
        $image_meta[ $meta_name ] = maybe_unserialize( array_pop( $meta_value ) );
    }

    $attachment_metadata = isset( $image_meta['_wp_attachment_metadata'] ) ? $image_meta['_wp_attachment_metadata'] : null;

    // Determine if we already have an image of this size
    if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {
        $intermediate_image_data = image_get_intermediate_size( $attachment_id, $intermediate_size );
        $image_url               = $intermediate_image_data['url'];
    } else {
        $image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
    }
// Not enough info so attempt to fallback
} else {

    if ( ! empty( $attachment_id ) ) {
        $image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
    } else {
        $image_url = false;
    }

}

if ( empty( $image_url ) && ! empty( $file_path ) ) {

    $image_meta = get_post_meta( $attachment_id, '_wp_attached_file' );

    if ( ! empty( $image_meta ) ) {
        $image_url = $uploads['baseurl'] . '/' . $image_meta[0];
    }
}

As still relatively new to php, and still learning, would appreciate any feedback or suggestions on how to overcome this error.

0

There are 0 answers