如何通过钩子在Elementor文章循环的图片后插入文本?
在Elementor文章循环的图片后插入自定义文本的正确方法
根据你的需求,分三种常见场景给出具体实现方案:
场景1:针对文章特色图片(Featured Image)
如果你的Elementor文章循环展示的是特色图片,用WordPress原生的post_thumbnail_html过滤器就能直接在图片HTML后追加内容:
add_filter( 'post_thumbnail_html', 'add_text_after_featured_image', 10, 5 ); function add_text_after_featured_image( $html, $post_id, $post_thumbnail_id, $size, $attr ) { // 排除Wishlist页面 if ( is_page( 'Wishlist' ) ) { return $html; } // 仅对文章类型生效 if ( 'post' !== get_post_type( $post_id ) ) { return $html; } // 获取ACF自定义字段值 $exclusive = get_field( 'exclusive', $post_id ); // 拼接要添加的文本(可自定义样式类) $custom_text = '<div class="custom-image-text">Custom Text Here ' . esc_html( $exclusive ) . '</div>'; return $html . $custom_text; }
场景2:针对Elementor图片小部件
如果循环里用的是Elementor自带的图片小部件,用Elementor专属钩子精准定位:
add_filter( 'elementor/widget/render_content', 'add_text_after_elementor_image_widget', 10, 2 ); function add_text_after_elementor_image_widget( $content, $widget ) { // 排除Wishlist页面 if ( is_page( 'Wishlist' ) ) { return $content; } // 仅对图片小部件生效 if ( 'image' !== $widget->get_name() ) { return $content; } // 仅对文章类型生效 if ( 'post' !== get_post_type() ) { return $content; } $post_id = get_the_ID(); $exclusive = get_field( 'exclusive', $post_id ); $custom_text = '<div class="custom-image-text">Custom Text Here ' . esc_html( $exclusive ) . '</div>'; return $content . $custom_text; }
场景3:针对文章正文中的所有图片
如果要给文章正文里的所有图片都加文本,用the_content过滤器替换图片标签:
add_filter( 'the_content', 'add_text_after_all_images_in_content' ); function add_text_after_all_images_in_content( $content ) { // 排除Wishlist页面 if ( is_page( 'Wishlist' ) ) { return $content; } // 仅对文章类型生效 if ( 'post' !== get_post_type() ) { return $content; } $exclusive = get_field( 'exclusive' ); $custom_text = '<div class="custom-image-text">Custom Text Here ' . esc_html( $exclusive ) . '</div>'; // 匹配所有img标签,在后面追加文本 $content = preg_replace( '/(<img[^>]+>)/', '$1' . $custom_text, $content ); return $content; }
注意事项
- 可以通过修改
custom-image-text类名,添加CSS样式美化文本显示 - 确保ACF插件已激活,
get_field函数才能正常获取自定义字段值 - 钩子优先级(代码中的
10)可根据需求调整,确保你的代码在其他插件之后执行
内容的提问来源于stack exchange,提问作者Yotam Dahan
相关产品推荐
相关产品推荐

