如何修复 PHP 警告:悬停时 WooCommerce 类别图像切换代码中未定义的数组键
P粉529581199
2023-08-27 00:13:53
[PHP讨论组]
<p>我的子主题functions.php 文件中有此代码:</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>它可以工作,并且可以在悬停时切换类别图像。</p>
<p>问题是显示与此行相关的 PHP 错误:</p><p>
$image_id = wc_get_product()->get_gallery_image_ids()[0] ;</p>
<p>错误是 PHP 警告:未定义的数组键 0</p>
<p>请问我该如何解决这个问题?</p>
<p>谢谢
塔姆辛</p>
<p>我还没有尝试修复。</p>
您可以首先检查
get_gallery_image_ids是否返回一个数组。如果存在,则检查键 0(第一个元素)是否存在。如果是这样,那么您就可以随意使用它。... // 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' ) ; }编辑,
您应该使用此代码编辑您的
mem_add_on_hover_shop_loop_image函数。最终代码应如下所示,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'); } }