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

如何让两个WordPress插件同时运行LearnDash的ld_lesson_access_from钩子?

解决LearnDash双插件钩子冲突及Topic专属过滤器问题

一、让两个ld_lesson_access_from钩子同时运行的方法

WordPress过滤器是链式执行的,只要满足以下条件,两个插件的钩子都会正常运行:

  • 确保回调函数始终返回参数
    所有过滤器回调必须在最后返回处理后的$access_from,哪怕没有修改值。如果省略return语句,后续过滤器会接收到null,导致逻辑异常。示例修正代码:

    // Plugin 1 修正写法
    add_filter( 'ld_lesson_access_from', array( __CLASS__, 'filter__ld_lesson_access_from_1' ), 999999, 3 );
    public static function filter__ld_lesson_access_from_1( $access_from, $lesson_id, $user_id ) {
        // 你的Lesson业务逻辑
        if ( some_condition() ) {
            $access_from = strtotime( '+7 days' ); // 示例修改访问时间
        }
        // 必须返回参数
        return $access_from;
    }
    
    // Plugin 2 修正写法
    add_filter( 'ld_lesson_access_from', array( __CLASS__, 'filter__ld_lesson_access_from_2' ), 99999, 3 );
    public static function filter__ld_lesson_access_from_2( $access_from, $lesson_id, $user_id ) {
        // 注意:第二个参数是lesson_id,若要处理Topic,需先判断类型
        if ( 'sfwd-topic' === get_post_type( $lesson_id ) ) {
            // 你的Topic业务逻辑
            if ( another_condition() ) {
                $access_from = strtotime( '+3 days' );
            }
        }
        // 必须返回参数
        return $access_from;
    }
    
  • 明确钩子参数类型
    ld_lesson_access_from的第二个参数是$lesson_id,但LearnDash中Topic也会触发这个钩子(因为Topic属于Lesson的子内容),所以可以通过get_post_type()判断当前处理的是Lesson还是Topic,再分别执行逻辑。

二、Topic专属的同款过滤器

LearnDash提供了专门针对Topic的访问时间过滤器:ld_topic_access_from,参数与ld_lesson_access_from完全一致:

  • $access_from:当前的访问开始时间戳
  • $topic_id:当前Topic的ID
  • $user_id:当前用户ID

推荐Plugin 2使用这个专属钩子,避免与Lesson的逻辑混淆,代码示例:

// Plugin 2 使用Topic专属钩子
add_filter( 'ld_topic_access_from', array( __CLASS__, 'filter__ld_topic_access_from_2' ), 10, 3 );
public static function filter__ld_topic_access_from_2( $access_from, $topic_id, $user_id ) {
    // 你的Topic专属业务逻辑
    if ( topic_specific_condition( $topic_id, $user_id ) ) {
        $access_from = strtotime( 'now' ); // 示例立即开放访问
    }
    return $access_from;
}

总结

  • 若坚持共用ld_lesson_access_from,核心是确保两个回调都返回参数,并通过post_type区分Lesson/Topic逻辑;
  • 更优方案是分别使用ld_lesson_access_from(处理Lesson)和ld_topic_access_from(处理Topic),实现逻辑解耦,避免冲突。

内容的提问来源于stack exchange,提问作者Parthavi Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:22:37