最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Custom code not working on lesson pages - Tutor LMS - Stack Overflow

programmeradmin4浏览0评论

I've created the following code in order to include navigation buttons at the top of my Tutor LMS courses. Their purpose is that the user can navigate between courses in a category. However, I can only get the buttons to appear on a 'course' page. It doesn't display on 'lesson' pages for some reason? I wonder if anyone could help? Thank you

 function tutor_navigation_buttons() {
        global $post;

    if (!$post) {
        return "No global post object found";
    }

    $post_type = get_post_type($post);

    // Adjusted: Check if post type is "courses", "tutor_lesson", or "lesson"
    if ($post_type === 'courses') {
        $current_post = $post; // Course page
    } elseif ($post_type === 'lesson') {
        $course_id = get_post_meta($post->ID, '_tutor_course_id_for_lesson', true);
        if (!$course_id) {
            return "No associated course found for this lesson (Lesson ID: {$post->ID})";
        }
        $current_post = get_post($course_id); // Get the parent course
    } else {
        return "Not on a course or lesson page (Detected post type: $post_type)";
    }

    // Extract module number from course title
    $current_title = get_the_title($current_post->ID);
    if (!preg_match('/Modiwl (\d+):/', $current_title, $matches)) {
        return "Could not extract module number from: $current_title";
    }

    $current_number = (int) $matches[1];
    $categories = wp_get_post_terms($current_post->ID, 'course-category', ['fields' => 'ids']);

    // Find Next and Previous Modules
    $next_module = get_adjacent_module($categories, $current_number + 1);
    $prev_module = get_adjacent_module($categories, $current_number - 1);

    // Start output
    ob_start();
    echo "";

    if ($prev_module) {
        $prev_link = get_permalink($prev_module->ID);
        echo "Modiwl blaenorol";
    }

    if ($next_module) {
        $next_link = get_permalink($next_module->ID);
        echo "Modiwl nesaf";
    }

    echo "";

    return ob_get_clean();
}

add_shortcode('tutor_navigation', 'tutor_navigation_buttons');

// Helper function to find the adjacent module by number
function get_adjacent_module($categories, $target_number) {
    $args = [
        'post_type'      => 'courses',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'tax_query'      => [
            [
                'taxonomy' => 'course-category',
                'field'    => 'id',
                'terms'    => $categories,
            ],
        ],
        's' => "Modiwl $target_number:",
    ];

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return null;
    }

    return $query->posts[0];
}
发布评论

评论列表(0)

  1. 暂无评论