· 6 years ago · Dec 16, 2019, 09:58 PM
1/**
2 * log_popular_categories
3 *
4 * This function logs popularity for categories when a user views an article on the website.
5 * How it works:
6 * * User is given a hash based on their IP, user agent, the post ID and the date
7 * * The hash is used to ensure that the popularity of the category only goes up once per user per post.
8 * * A single user can traverse many articles in a category and that would increase the popularity for that category.
9 * * However, a single user can only increase the popularity of a category once per post per day.
10 * * Data is saved in the wp_options table under the option name: popular_categories_{category_id}
11 * * This will later be retrieved by a WP CRON function that will parse the actual popularity.
12 */
13function log_popular_categories() {
14 global $post;
15
16 // Only run if we're on a single page.
17 if ( is_single( get_the_ID() ) ) {
18 $id = get_the_ID(); // Get the ID
19 $date = date( 'mdY' ); // Get the current date.
20 $categories = get_the_terms( $id, 'category' ); // Get all the categories associated with this post.
21
22 $hash = md5( $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $id . $date ); // Generate a hash. This is used to ensure that page reloads don't duplicate the popularity.
23
24 // Continue if there are categories associated with this post.
25 if ( $categories !== false ) {
26
27 // Loop through each category on the page and log each of the categories in the options table.
28 foreach ( $categories as $cat ) {
29
30 $options_name = 'popular_categories_' . $cat->term_id;
31 $options_value = null;
32
33 $current_option_value = get_option( $options_name ); // Returns serialized string or false.
34
35
36 if ( $current_option_value !== false ) {
37 // Option exists, unserialize the data, and add values.
38 $options_value = unserialize( $current_option_value );
39
40
41 if ( isset( $options_value[ $date ] ) ) {
42 // Today's date is in the array.
43
44 $options_value[ $date ][] = $hash; // Add the hash to the existing array.
45 $options_value[ $date ] = array_unique( $options_value[ $date ] ); // Filter out duplicate hashes.
46 } else {
47 // Today's date is not in the array.
48 $options_value[ $date ] = array( $hash ); // Create an array for the current date and fill it with the hash.
49 }
50
51 update_option( $options_name, serialize( $options_value ) ); // Save to the database
52
53 } else {
54 // Option doesn't exist, create it.
55
56 $options_value = array(
57 date( 'mdY' ) => array( $hash )
58 );
59 update_option( $options_name, serialize( $options_value ) ); // Save to the database
60 }
61 }
62 }
63 }
64}