WordPress创建Shortcode展示自定义分类法术语及图片的问题排查
自定义分类法展示短代码问题与修正方案
现有代码存在的问题
- 短代码输出逻辑错误:WordPress短代码规范要求必须return输出内容,不能直接print/echo,否则会出现内容显示位置错位的问题
- 术语图片获取方法不匹配:你使用ACF插件创建的分类图片字段,不能调用
taxonomy-images-get-terms过滤器(该接口属于Taxonomy Images插件,未安装对应插件时无法获取数据),需使用ACF官方的get_field()方法读取字段值 - 图片输出语法错误:
wp_get_attachment_image()返回的是完整的img标签,不能放入img的src属性中,如需获取图片地址应使用wp_get_attachment_image_url()函数 - 术语名称输出错误:循环内调用
get_terms()会返回全部分类术语数组,无法输出当前循环的单个术语名称,应直接读取$term->name - HTML结构错误:包裹图片的div闭合标签缺少
>,会导致整个页面布局错乱 - 换行逻辑无效:每3个术语换行的代码没有做输出处理,不会生成对应的行结构
- 函数名存在冲突风险:直接使用
countries作为函数名过于通用,容易和其他主题/插件的函数重名导致报错
修正后的完整代码
首先修改countries.php文件代码:
<?php // 加前缀避免函数名冲突 function custom_countries_shortcode() { // 初始化输出字符串 $output = ''; // 获取countries分类下的所有已发布术语 $terms = get_terms([ 'taxonomy' => 'countries', 'hide_empty' => false, // 设为true可隐藏没有文章的术语 ]); if (!empty($terms) && !is_wp_error($terms)) { $i = 1; $output .= '<div class="elementor-row">'; foreach ($terms as $term) { // 替换为你在ACF中设置的图片字段名 $image_id = get_field('你设置的ACF图片字段名', $term); $term_link = get_term_link($term, $term->taxonomy); $term_name = $term->name; $output .= '<div class="elementor-column elementor-col-33 elementor-top-column elementor-element" data-element_type="column"> <div class="text-center p-3"> <div> <a href="' . esc_url($term_link) . '"> ' . wp_get_attachment_image($image_id, 'ib', false, ['alt' => esc_attr($term_name)]) . ' </a> </div> <p class="sl-text mt-3">' . esc_html($term_name) . '</p> </div> </div>'; // 每3个术语换一行 if ($i % 3 == 0 && $i != count($terms)) { $output .= '</div><div class="elementor-row">'; } $i++; } $output .= '</div>'; } // 返回最终内容符合短代码规范 return $output; } add_shortcode('countries', 'custom_countries_shortcode');
注意:代码中
你设置的ACF图片字段名需要替换为你在ACF后台为countries分类法创建的图片字段的实际字段名。
functions.php中的注册代码无需修改,保持原有代码即可:
require_once('shortcodes/countries.php');
内容的提问来源于stack exchange,提问作者Elero Obaitan
相关产品推荐
相关产品推荐

