How to get the current courseid for the current page in moodle

Learn how to get the current courseid for the current page in moodle with practical examples, diagrams, and best practices. Covers moodle development techniques with visual explanations.

How to Get the Current Course ID in Moodle

Hero image for How to get the current courseid for the current page in moodle

Discover various methods to programmatically retrieve the current course ID within Moodle, essential for custom development and plugin creation.

When developing custom Moodle plugins, themes, or local modifications, a common requirement is to identify the courseid of the page currently being viewed. This ID is crucial for fetching course-specific data, applying contextual logic, or ensuring your code operates within the correct Moodle course context. This article explores several reliable methods to obtain the current course ID, catering to different Moodle contexts and development scenarios.

Understanding Moodle's Context System

Moodle uses a robust context system to manage permissions and data access. Every Moodle page, activity, and block exists within a specific context, which is hierarchical. The course context is a fundamental level in this hierarchy. Understanding how to navigate this context is key to retrieving the courseid reliably.

flowchart TD
    A[User Accesses Moodle Page]
    A --> B{Is 'id' parameter present in URL?}
    B -->|Yes| C[Page is Activity or Course View]
    C --> D{Use `$PAGE->cm->course` or `$PAGE->course->id`}
    B -->|No| E{Is 'courseid' parameter present in URL?}
    E -->|Yes| F[Page is Course-related but not Activity]
    F --> G[Use `optional_param('courseid', 0, PARAM_INT)`]
    E -->|No| H[Fallback: Check `$PAGE->context`]
    H --> I{Is context a 'course' type?}
    I -->|Yes| J[Use `$PAGE->context->instanceid`]
    I -->|No| K[Traverse up context hierarchy]
    K --> L[Find first 'course' context]
    L --> M[Use `$course->id` from found context]
    M --> N[Course ID Found]
    D --> N
G --> N

Decision flow for retrieving the current course ID in Moodle.

Method 1: Using the Global $PAGE Object

The global $PAGE object is Moodle's primary way to manage page-specific information. It's available in almost all Moodle pages and provides direct access to the current course and activity module (if applicable). This is often the most straightforward and recommended approach.

<?php

require_once(__DIR__ . '/../../config.php');

// Ensure $PAGE is available (it usually is in Moodle pages)
global $PAGE;

$courseid = 0;

// Method A: If on a course page or activity page
if (isset($PAGE->course) && $PAGE->course->id) {
    $courseid = $PAGE->course->id;
} else if (isset($PAGE->cm) && $PAGE->cm->course) {
    // Method B: If on an activity page (e.g., mod/forum/view.php)
    $courseid = $PAGE->cm->course;
}

if ($courseid) {
    echo "Current Course ID: " . $courseid;
} else {
    echo "Could not determine current Course ID from \$PAGE object.";
}

?>

Method 2: Retrieving from URL Parameters

Many Moodle pages pass the courseid or id (for activity modules) as a URL parameter. You can directly retrieve these parameters using Moodle's optional_param function, which is safer than directly accessing $_GET as it handles type casting and default values.

<?php

require_once(__DIR__ . '/../../config.php');

// Get courseid if explicitly passed in the URL
$courseid = optional_param('courseid', 0, PARAM_INT);

// If courseid is not found, check for 'id' which might be an activity ID
// and then resolve the course from that activity.
if (!$courseid) {
    $cmid = optional_param('id', 0, PARAM_INT);
    if ($cmid) {
        // Get the course module record
        $cm = get_coursemodule_from_id(null, $cmid);
        if ($cm) {
            $courseid = $cm->course;
        }
    }
}

if ($courseid) {
    echo "Current Course ID from URL/Activity: " . $courseid;
} else {
    echo "Could not determine current Course ID from URL parameters.";
}

?>

Method 3: Using the Context API

For more advanced scenarios, especially when dealing with contexts that are not directly a course (e.g., a block context within an activity), you might need to traverse the context hierarchy. Moodle's context_course::instance_by_id or context_module::instance_by_id can help, but often you'll start from the current page's context and work upwards.

<?php

require_once(__DIR__ . '/../../config.php');

global $PAGE;

$courseid = 0;

// Start with the current page's context
if (isset($PAGE->context)) {
    $context = $PAGE->context;

    // Loop up the context hierarchy until a course context is found
    while ($context && $context->contextlevel != CONTEXT_COURSE) {
        $context = $context->get_parent_context();
    }

    if ($context && $context->contextlevel == CONTEXT_COURSE) {
        $courseid = $context->instanceid;
    }
}

if ($courseid) {
    echo "Current Course ID from Context API: " . $courseid;
} else {
    echo "Could not determine current Course ID using Context API.";
}

?>

Choosing the Right Method

The best method depends on your specific use case and where your code is executing. For most standard Moodle pages (course views, activity views), using the $PAGE object is the most direct and efficient. If you're in a script that might not have $PAGE fully initialized or are processing a URL directly, optional_param is a good alternative. For complex scenarios involving blocks or deeply nested contexts, the Context API provides the most robust solution.