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

Tutor LMS 如何通过课程ID或文章ID获取关联的Woocommerce产品

解决方案

实现逻辑

你可以通过自定义字段存储课程ID和WooCommerce产品ID的关联关系,再在课程详情页的内容中插入关联产品的展示模块,完整可运行代码如下:

add_filter( 'the_content', 'codemode__show_linked_product' );
function codemode__show_linked_product( $content ){
    global $post;

    // 仅在单篇课程详情页执行逻辑
    if( is_singular( 'courses' ) && get_post_type( $post ) === 'courses' ){
        $course_id = $post->ID;
        // 从自定义字段读取关联的WooCommerce产品ID,可替换为你实际使用的关联字段键名
        $linked_product_id = get_post_meta( $course_id, 'linked_woo_product_id', true );
        
        // 校验产品ID有效、对应产品存在
        if ( !empty($linked_product_id) && wc_get_product( absint($linked_product_id) ) ) {
            // 构造产品展示区域
            $product_section = '<div class="course-linked-product" style="padding: 16px; border: 1px solid #e5e7eb; border-radius: 8px; margin: 24px 0;">';
            $product_section .= '<h3>课程配套购买产品</h3>';
            // 调用WooCommerce内置短代码渲染产品卡片,也可自定义输出产品信息
            $product_section .= do_shortcode( '[product id="' . absint($linked_product_id) . '"]' );
            $product_section .= '</div>';

            // 将产品模块拼接在课程内容末尾,如需放在开头可改为 $content = $product_section . $content
            $content .= $product_section;
        }
    }

    return $content;
}

使用说明

  • 你需要先给courses自定义文章类型添加键名为linked_woo_product_id的自定义字段,在编辑课程时填入对应关联的WooCommerce产品ID即可
  • 如果你使用的是LearnDash、LifterLMS等主流课程插件,它们已内置WooCommerce关联能力,直接替换$linked_product_id的获取逻辑即可:
    • LearnDash:$linked_product_id = get_post_meta( $course_id, '_related_products', true );
    • LifterLMS:$linked_product_id = get_post_meta( $course_id, '_llms_product_id', true );
  • 如果需要关联多个产品,将自定义字段设置为允许多值,遍历输出产品列表即可

内容的提问来源于stack exchange,提问作者Karue Benson Karue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:04