You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WordPress中使用短代码显示自定义文章元数据求助

自定义Testimonial短代码实现方案

你已经创建了Testimonials自定义文章类型,以及存储在postmeta表的testimonial-author、testimonial-company自定义字段,下面给你一个统一的短代码,能一次性展示 testimonial 正文、作者和公司信息,比你之前单独调用字段的方式更高效:

// 注册统一的 testimonial 展示短代码
add_shortcode('display_testimonial', 'display_testimonial_func');

function display_testimonial_func($atts) {
    // 设置短代码默认参数,支持指定 testimonial 文章ID
    $atts = shortcode_atts(array(
        'id' => get_the_ID()
    ), $atts);

    // 校验目标文章是否为Testimonials类型
    $post_type = get_post_type($atts['id']);
    if ($post_type !== 'Testimonials') {
        return '<p>请指定有效的Testimonials文章ID</p>';
    }

    // 获取自定义字段及正文内容
    $author = get_post_meta($atts['id'], 'testimonial-author', true);
    $company = get_post_meta($atts['id'], 'testimonial-company', true);
    $testimonial_text = get_post_field('post_content', $atts['id']);

    // 组装展示内容,自动处理空字段
    $output = '<div class="testimonial-container">';
    $output .= '<blockquote>' . wpautop($testimonial_text) . '</blockquote>';
    if ($author) {
        $output .= '<p class="testimonial-meta">—— ' . esc_html($author);
        $output .= $company ? ',' . esc_html($company) : '';
        $output .= '</p>';
    }
    $output .= '</div>';

    return $output;
}

使用说明:

  • 在Testimonials文章内调用:直接插入短代码 [display_testimonial],会自动读取当前文章的所有内容;
  • 在其他页面调用指定 testimonial:传入文章ID即可,比如 [display_testimonial id="456"](把456换成你实际的Testimonials文章ID);
  • 样式自定义:可以通过.testimonial-container、.testimonial-meta这些CSS类来调整排版样式。

为什么不用你原来的代码?

你之前的短代码只能单独获取作者字段,要展示完整 testimonial 得插多个短代码,而且没做类型校验和内容转义,上面的代码不仅整合了所有需要的内容,还加了安全校验,避免无效调用的问题。

内容的提问来源于stack exchange,提问作者Donna Hall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:05:18