PluginProbe
Passster – Password Protect Pages and Content / 4.3.12
Passster – Password Protect Pages and Content v4.3.12
4.3.15 4.3.14 4.3.12 4.3.13 4.3.11 4.3.10 4.3.9 4.3.8 4.3.7 4.3.6 4.3.5 trunk 3.5.4 3.5.5.2 3.5.5.8 3.5.5.9 4.0 4.1.4 4.2.10 4.2.11 4.2.12 4.2.13 4.2.14 4.2.15 4.2.16 All 47 releases
content-protector / inc / class-ps-protected-posts.php

class-ps-protected-posts.php in Passster – Password Protect Pages and Content 4.3.12, at inc/class-ps-protected-posts.php

100 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace passster;
4
5 /**
6 * Class to handle protected posts functionality
7 */
8 class PS_Protected_Posts {
9
10 /**
11 * Contains instance or null
12 *
13 * @var object|null
14 */
15 private static $instance = null;
16
17 const PASSTER_META_KEY = 'passster_activate_protection';
18 /**
19 * Returns instance of PS_Protected_Posts.
20 *
21 * @return object
22 */
23 public static function get_instance() {
24 if ( null === self::$instance || ! self::$instance instanceof PS_Protected_Posts ) {
25 self::$instance = new PS_Protected_Posts();
26 }
27
28 return self::$instance;
29 }
30
31 /**
32 * Constructor
33 */
34 public function __construct() {
35 add_filter( 'pre_get_posts', array( $this, 'exclude_protected_posts_from_search' ) );
36 }
37
38 /**
39 * Exclude protected posts from search results for non-logged in users
40 *
41 * @param \WP_Query $query The WP_Query instance.
42 * @return \WP_Query
43 */
44 public function exclude_protected_posts_from_search( $query ) {
45 if ( ! $this->should_exclude_from_search( $query ) ) {
46 return $query;
47 }
48
49 $meta_query = array(
50 'relation' => 'AND',
51 array(
52 'relation' => 'OR',
53 array(
54 'key' => self::PASSTER_META_KEY,
55 'compare' => 'NOT EXISTS',
56 ),
57 array(
58 'key' => self::PASSTER_META_KEY,
59 'value' => '1',
60 'compare' => '!=',
61 ),
62 ),
63 );
64
65 $existing_meta_query = $query->get( 'meta_query', array() );
66 if ( ! empty( $existing_meta_query ) ) {
67 $meta_query = array_merge( array( 'relation' => 'AND' ), $existing_meta_query, array( $meta_query ) );
68 }
69
70 $query->set( 'meta_query', $meta_query );
71
72 return $query;
73 }
74
75 /**
76 * Check if we should exclude protected posts from this query
77 *
78 * @param \WP_Query $query The WP_Query instance.
79 * @return boolean
80 */
81 private function should_exclude_from_search( $query ) {
82 // Skip if user is logged in as admin
83 if ( current_user_can( 'manage_options' ) ) {
84 return false;
85 }
86
87 // Check for regular search
88 if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) {
89 return true;
90 }
91
92 // Check for REST API search
93 if ( defined( 'REST_REQUEST' ) && REST_REQUEST && ! empty( $query->query_vars['s'] ) ) {
94 return true;
95 }
96
97 return false;
98 }
99 }
100