How to fix PHP warning: undefined array key in WooCommerce category image switching code on hover
P粉529581199
P粉529581199 2023-08-27 00:13:53
0
1
551
<p>I have this code in my child theme's functions.php file: </p> <pre class="brush:php;toolbar:false;">// add hover image to woo category page add_action( 'woocommerce_before_shop_loop_item_title', 'mem_add_on_hover_shop_loop_image' ) ; function mem_add_on_hover_shop_loop_image() { $image_id = wc_get_product()->get_gallery_image_ids()[0]; if ( $image_id ) { echo wp_get_attachment_image( $image_id, 'woocommerce_thumbnail' ) ; } else { //echo wp_get_attachment_image( wc_get_product()->get_image_id() ) ; echo wp_get_attachment_image( wc_get_product()->get_image_id(), 'woocommerce_thumbnail' ) ; } }</pre> <p>It works and switches category images on hover. </p> <p>The problem is showing a PHP error related to this line: </p><p> $image_id = wc_get_product()->get_gallery_image_ids()[0] ;</p> <p>The error is PHP warning: undefined array key 0</p> <p>How can I solve this problem? </p> <p>Thank you Tamsin</p> <p>I haven't tried the fix yet. </p>
P粉529581199
P粉529581199

reply all(1)
P粉011684326

You can first check if get_gallery_image_ids returns an array. If it exists, check if key 0 (the first element) exists. If so, then you're free to use it however you want.

...

// Get all IDs
$idList = wc_get_product()->get_gallery_image_ids(); 

// Check if the IDs are an array and key 0 (first element) exists
if (is_array($idList) && array_key_exists(0, $idList)) {
    // Get the first element
    $image_id = $idList[0];

    echo wp_get_attachment_image($image_id, 'woocommerce_thumbnail' ) ; 
} else { 
    echo wp_get_attachment_image(wc_get_product()->get_image_id(), 'woocommerce_thumbnail' ) ; 
}

edit,

You should edit your mem_add_on_hover_shop_loop_image function with this code. The final code should look like this,

add_action('woocommerce_before_shop_loop_item_title', 'mem_add_on_hover_shop_loop_image');
function mem_add_on_hover_shop_loop_image()
{
    // Get all IDs
    $idList = wc_get_product()->get_gallery_image_ids();

    // Check if the IDs are an array and key 0 (first element) exists
    if (is_array($idList) && array_key_exists(0, $idList)) {
        // Get the first element
        $image_id = $idList[0];

        echo wp_get_attachment_image($image_id, 'woocommerce_thumbnail');
    } else {
        echo wp_get_attachment_image(wc_get_product()->get_image_id(), 'woocommerce_thumbnail');
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template