-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsloisel-random-post.php
64 lines (51 loc) · 1.51 KB
/
csloisel-random-post.php
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
<?php
/**
* Plugin Name: CSLoisel Random Post
*/
class CSLoisel_Random_Post {
const COOKIE_KEY = 'CSLSeenRandomPosts';
public static function init() {
add_filter( 'theme_page_templates', function( $templates ) {
$templates['random-post.php'] = 'Random Post';
return $templates;
} );
add_filter( 'wp', function( $template ) {
$template_slug = get_page_template_slug();
if ( 'random-post.php' === $template_slug ) {
self::setup_random_post();
}
} );
}
public static function get_random_post() {
$args = array(
'orderby' => 'rand',
'post_type' => 'post',
'posts_per_page' => 1,
'post__not_in' => self::get_seen_posts(),
'post_status' => 'publish'
);
$query = new WP_Query( $args );
return $query->posts[0];
}
public static function setup_random_post() {
$random_post = self::get_random_post();
$args = array(
'p' => $random_post->ID
);
query_posts( $args );
$GLOBALS['post'] = $random_post;
}
public static function get_seen_posts() {
$seen_ids = !empty( $_COOKIE[ self::COOKIE_KEY ] ) ? json_decode( $_COOKIE[ self::COOKIE_KEY ] ) : array();
$seen_ids = array_map( 'intval' , $seen_ids );
$seen_ids = array_filter( $seen_ids );
return $seen_ids;
}
public static function store_seen_post( $wp ) {
$post_id = get_queried_object_id();
$seen_ids = self::get_seen_posts();
$seen_ids[] = $post_id;
setcookie( self::COOKIE_KEY, json_encode( $seen_ids ), time() + MONTH_IN_SECONDS );
}
}
add_action( 'init', array( 'CSLoisel_Random_Post', 'init' ) );