custom field can be added from site admin, following code can help to get custom field value as per course object or course id.
// $course from course record from database table
if ($course instanceof stdClass) {
$course = new core_course_list_element($course);
}
$handler = \core_customfield\handler::get_handler('core_course', 'course');
$customdata = (array)$handler->export_instance_data_object($course->id);
$final= [];
foreach($course->get_custom_fields() as $field){
if($handler->can_view($field->get_field(), $course->id)){
if(array_key_exists($field->get_field()->get('shortname'), $customdata)){
$final[$field->get_field()->get('shortname')] = array(
'name' =>$field->get_field()->get('name'),
'shortname' =>$field->get_field()->get('shortname'),
'description' =>$field->get_field()->get('description'),
'type' =>$field->get_field()->get('type'),
'data' =>$customdata[$field->get_field()->get('shortname')]
);
}
}
}
// return output like
// array (array("name"=>"field visible name","shortname"=>"field shortname", "description"=>"field description","type"=>"field type | text| checkbox","data"=>"field data"))