Repository navigation
Expand file tree
/
Copy pathPrivate_Course_Access.php
More file actions
117 lines (99 loc) · 2.56 KB
/
Copy pathPrivate_Course_Access.php
File metadata and controls
117 lines (99 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* Private Course Access
*
* @package Tutor\Course
* @author Themeum <support@themeum.com>
* @link https://themeum.com
* @since 1.0.0
*/
namespace TUTOR;
use Tutor\Cache\TutorCache;
use Tutor\Models\CourseModel;
use Tutor\Models\EnrollmentModel;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Register Tutor's post types
*
* @since 1.0.0
*/
class Private_Course_Access extends Tutor_Base {
/**
* Allow empty
*
* @var boolean
*/
private $allow_empty = false;
/**
* Register hooks
*
* @since 1.0.0
*/
public function __construct() {
parent::__construct();
add_action( 'pre_get_posts', array( $this, 'enable_private_access' ) );
add_filter( 'post_type_link', array( $this, 'permalink_for_private_course' ), 10, 2 );
}
/**
* Enable private course access
*
* @param mixed $query query.
*
* @return void
*/
public function enable_private_access( $query = null ) {
if ( ! is_admin() && is_user_logged_in() ) {
global $wpdb;
$p_name = isset( $query->query['name'] ) ? $query->query['name'] : '';
$p_name = esc_sql( $p_name );
if ( $this->allow_empty && empty( $p_name ) ) {
$query->set( 'post_status', array( 'private', 'publish' ) );
return;
}
// Get using raw query to speed up.
$course_post_type = tutor()->course_post_type;
// Get data from cache.
$cache_key = "tutor_private_query_{$course_post_type}_{$p_name}";
$result = TutorCache::get( $cache_key );
if ( false === $result ) {
$private_query = $wpdb->prepare(
"SELECT ID, post_parent
FROM {$wpdb->posts}
WHERE post_type = %s
AND post_name = %s
AND post_status = %s
",
$course_post_type,
$p_name,
'private'
);
$result = $wpdb->get_results( $private_query ); //phpcs:ignore
// Set cache data.
TutorCache::set( $cache_key, $result );
}
$private_course_id = ( is_array( $result ) && isset( $result[0] ) ) ? $result[0]->ID : 0;
if ( $private_course_id > 0 && EnrollmentModel::is_enrolled( $private_course_id ) ) {
$this->allow_empty = true;
$query->set( 'post_status', array( 'private', 'publish' ) );
}
}
}
/**
* Make permalink for private course.
*
* @since 3.0.0
*
* @param string $url permalink.
* @param WP_Post $post post object.
*
* @return string
*/
public function permalink_for_private_course( $url, $post ) {
if ( CourseModel::STATUS_PRIVATE === $post->post_status && $this->course_post_type === $post->post_type ) {
$url = home_url( $this->course_base_permalink . '/' . $post->post_name );
}
return $url;
}
}