How to fix PHP warning: undefined array key in WooCommerce category image switching code on hover
P粉529581199
2023-08-27 00:13:53
<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>
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.edit,
You should edit your
mem_add_on_hover_shop_loop_image
function with this code. The final code should look like this,