如何修改WordPress自定义函数以返回次要图片的SRC属性?
修改WordPress函数以返回次要图片URL而非直接输出
我来帮你解决这个问题!你的核心需求是把原来直接输出图片URL的函数改成返回值,这样就能用变量接收了对吧?原来的函数用echo直接输出内容,所以你用$myvariable = haruki(...)的时候,变量拿到的其实是null——因为函数根本没有返回任何东西。
下面给你两种修改方案,根据你的实际需求选择:
方案1:返回所有次要图片的URL数组
如果你想获取当前文章所有非特色图片的URL,可以把这些URL收集到数组里,最后返回这个数组:
function haruki($post_id) { $thumbnail_ID = get_post_thumbnail_id($post_id); // 传入post_id,避免全局变量依赖 $images = get_children( array( 'post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ); $img_urls = array(); // 初始化数组存储URL if ($images) : foreach ($images as $attachment_id => $image) : if ( $image->ID != $thumbnail_ID ) : $img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); if ($img_alt == '') : $img_alt = $image->post_title; endif; $big_array = image_downsize( $image->ID, 'large' ); $img_url = $big_array[0]; $img_urls[] = $img_url; // 将URL加入数组,替代原来的echo endif; endforeach; endif; return $img_urls; // 返回所有次要图片的URL数组 }
使用方法:
// 获取当前文章的所有次要图片URL数组 $secondary_images = haruki(get_the_ID()); // 遍历输出(示例) foreach ($secondary_images as $url) { echo '<img src="' . esc_url($url) . '" alt="" />'; }
方案2:只返回第一个次要图片的URL
如果你只需要第一个非特色图片的URL,可以找到符合条件的图片后直接返回,不用遍历所有:
function haruki($post_id) { $thumbnail_ID = get_post_thumbnail_id($post_id); $images = get_children( array( 'post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ); if ($images) : foreach ($images as $attachment_id => $image) : if ( $image->ID != $thumbnail_ID ) : $big_array = image_downsize( $image->ID, 'large' ); return $big_array[0]; // 找到第一个就返回URL endif; endforeach; endif; return false; // 如果没有次要图片,返回false作为标记 }
使用方法:
// 获取第一个次要图片的URL $secondary_image = haruki(get_the_ID()); // 存在图片时输出(示例) if ($secondary_image) { echo '<img src="' . esc_url($secondary_image) . '" alt="" />'; }
额外优化说明
我特意修改了get_post_thumbnail_id()的调用,传入$post_id参数——这样即使全局$post变量不是你目标的文章,函数也能正确获取对应文章的特色图片,避免潜在的逻辑bug。
内容的提问来源于stack exchange,提问作者D. Dragon
相关产品推荐
相关产品推荐

