WordPress: Modify Native Calendar Widget for Event Post Types

Recently I was working on WordPress website  and the client’s theme had an existing “Event” custom post type. The client wanted a way to calendarize the event start date and display with a widget.

There is a calendar widget built into WordPress; however, it has a couple shortcomings for what the client was trying to do. First, it calendarises all posts regardless of type (and in this case all we want is event posts). Secondly, it also calendarises posts based on date posted rather than a field such as event date.  As an added constraint, the non-profit client did not have a budget for building a custom plugin from scratch to fill the need.

So I went digging through the PHP script that powers the native calendar widget and found a way to modify the plugin while only having to bill about a half hour of custom development. It actually took me longer to write this post!

It’s not the most ideal or elegant solution but it saved the client a bunch of money by spending almost no time on this.  Couple drawbacks without further modifications 1) the widget won’t display multi-day events properly 2) The calendar widget now only works with event post types (i.e., can’t calendarize post dates of normal blog posts).

Here’s what it ends up looking like:

The Code

PHP

The file I had to modify is located in the WordPress 3.5 installation in wordpressroot>wp-includes>general-template.php

In order to know which days on the calendar to highlight as links to posts, the WordPress devlopers built a query that pulls the day numbers of the posts that were posted in the current month.

There’s a couple issues here as it relates to getting this to work for events as opposed to regular posts. First, the query is pulling post_type equal to “post” so we’ll need to change that “event” so only events are being pulled. Secondly, the original query is selecting posts based on post date in the current month.   For events, when we’re looking at a calendar, we don’t care when it was posted, but rather the start date of the event.

To deal with these issues, I had to rewrite the query. Unfortunately, the event start date field was one of the custom fields added for the event post type so it resides in the `wp_postmeta` table as opposed to `wp_posts so you have to join the `wp_posts` and `wp_postmeta` tables to get access to all the required fields.  The query returns the event start day of the month (dom) , post id (post_id) , url of the event (guid) and event title (post_title).  You’ll see soon why I pulled more fields than just the day numbers like before. Also, I changed the return value to an array of objects instead of numerical array per my own preferences. The new query looks something like this:

The next block of the original code (see gist below) executes a second query almost identical to the first, but instead of pulling just day numbers like before, it pulls the post id, post titles and day numbers. The block following the query goes through each post and puts the titles into an associative array indexed by the day of the month. The array of post titles ($ak_titles_for_day) will used to display the post titles on their corresponding day cell in the calendar when it builds out the calendar table.

Use of two queries seemed a bit duplicative to me since they are so similar so I got rid of the second one and pulled the additional fields in the first query.  Next I modified the foreach to record both the event title and event page url for every event post (this is so we can display a list of event links when a user hovers over a calendar day). I also consolidated the foreach code with the loop that follows the first query.  Based on the results form the first query, two arrays are built.  The first array, $dayswithpost, is simply an array containing all the day numbers of the month that have events to be used when building out the calendar table. The $ak_titles_for_day array, as mentioned above, is an associative array indexed by day numbers. It stores the event title and event url under the corresponding day number index and will be used to display to the user when they hover over a day number on the calendar that has event starting dates.

Lastly, the  code to build out the table/calendar had to be modified.  The original block of code compares the day number of the calendar cell being generated to the $dayswithposts array to determine if any posts are listed for that day.  If the day number has corresponding posts in the $dayswithposts array, an anchor tag is wrapped around the day number and href generated using the built in WordPress function get_day_link(). This function returns the url of an archive page for all posts on a given day. This works nicely for days with multiple posts because you can see all the posts by navigating to that daily archive url which is a built in WordPress template. The post title(s) for days with posts are also inserted into the title attribute of the day number link from the values stored in the $ak_titles_for_day array so the user will see the post titles when they hover over a calendar day link.

For events, a single anchor wrapped around the calendar day number would not work because clicking on the day would just take you to the archive page for events posted on that day not the start date of actual event day.  Therefore the code needs to be modified so that a user is able to click on each individual event title and have it link to the events page url instead of an archive page.

Instead of wrapping the day number in an anchor tag, I switched it to a span so it can be selected later by css/js.  Also, I created a <div> containing event titles and links for all the events for a given day and inserted it after the calendar number </span>.  In the CSS, I set the <div> to display:none, and position:absolute and positioned it relative to the <td> it resides in.  Then using jQuery I set a hover on both the <span> and the <div> so when a user hovers over a day with posts, you can display the <div> with the event links and titles.

JS and CSS

Brainstorming: Can Google Trends Data Help Predict the Stock Market? Maybe…maybe not

According to a study by researchers at the University of Warwick Business School, using publicly available data on financial related search terms from Google Trends may help predict what the stock market will do.

In the study titled “Quantifying Trading Behavior in Financial Markets Using Google Trends” researchers tracked about 100 financially related terms such as “debt,” “crisis” and “derivatives” from 2004 to 2011.

In order to test their theory, the researchers created an investing “game” to see if the terms searched in the previous week to any given closing day could predict the Dow Jones Industrial Average (DIJA).  If searches for financial terms went down, they opted to buy and hold stocks.  Conversely, search term volumes went up, the researchers would sell assuming that the stocks were going to fall in value.

The game follows the logic that if people get anxious about the stock market, they will likely seek out information on financial issues before trying to get rid of their stock.  It almost goes without saying, the first place people go when seeking information on just about anything is Google.   So then, the idea was that finance-related searches on Google should spike before a stock market decline and vice versa.   Thanks to Google Trends, the public now has access to aggregated information on the volume of queries for different search terms and how these volumes change over time.

The researchers further found that “debt” was the most reliable term for predicting market fluctuations.  By buying when “debt” search volumes dropped and selling when the volumes rose, the researchers were able to increase their hypothetical portfolio by 326%.  The chart below from the research report illustrates these results:

rpt-strategies

 

 

 

 

 

 

 

The second chart, also from the report, shows the relative search volume change for the term “debt”  vs. time series of closing prices for the DIJA on the first day of trading each week.   If you look closely, immediately after every bright red spike in volume change, the index values drop and vice versa.

rpt-index

 

 

 

 

 

 

 

 

 

 

If you are like me, the results from the study immediately brought out my skeptical side so I figured I’d play around with Google Trends myself.   I compared the Google Trends volume reports for “debt” vs the DIJA for the month of January and April 2013.  As you see below, there is an inverse correlation:

trends

I’m still not completely sold, however, since it’s always easy to look back at data and make obvious correlations. It’s another thing to predict future movements of the market.  Obviously, there are many factors that influence a market participant’s decisions other than information obtained through Google searches and an unlimited number of factors that affect stock prices.

There will never be a “silver bullet” for predicting the market but the idea behind this study is certainly intriguing and could potentially be used to create another tool to be used by investors in making informed decisions about the market.  For example, this study was done at the “macro” level focusing on vague terms such as “debt” and analyzing an index that represents the broad market.   What if the same concept could be applied to market segments or even down to individual stocks whose prices are particularly affected by investor sentiment such as Apple.   Is it possible that analyzing a certain set of Apple related search terms could provide similar results as the original study at the individual company level?

Maybe or maybe not… but who wants to give me some money to play with to find out?  :)

 

HTTPs, Reverse Proxys, and Port 80!?

Recently we were getting ready to deploy a new project which functions only over SSL.  The project is deployed on AWS using the Elastic Load Balancers (ELB).  We have the ELB doing the SSL termination to reduce the load on the server and to help simply management of the SSL certs.  Anyways the the point of this short post.  One of the developers noticed that on some of the internal links she kept getting a link something like “https://dev.app.com:80/….”, it was properly generating the link to HTTPS but then specify port 80. Of course your browser really does not like that as its conflicting calls of port 80 and 443.  After a quick look into the project we found that we had yet to enable the proxy headers and specify the proxy(s), it was we had to turn on `trust_proxy_headers`.  However, doing this did not fix the issue.  You must in addition to enable the headers specify which ones you trust.  This can be easily done via the following:

Here is a very simple example of how you could specify them. You just let it know the IP’s of the proxy(s) and it will then properly generate your links.

You can read up on this more in the Symfony documentation on trusting proxies.

Anyways just wanted to put throw this out there incase you see this and realize you forgot to configure the proxy in your app!

Symfony2 and Impersonating Users, a Heads Up

Recently I was working on a project in which it admins were able to impersonate other users.  It’s a fairly easy task to add to Symfony2, merely adding a switch_user reference to your firewall can make it possible, consult the Symfony docs for more on that.  One thing I noticed was that every now and then when testing I would get weird errors after switching between multiple users, however it didn’t always happen.  After some digging around, it turns out when you switch user it does not clear that sessions attributes, ie if you set attribute ‘hello’ to value ‘world’ it would persist after you’ve impersonated another user.  This caused a few issues as on this application we used the session to store a few things like which set of database connections you currently use.

After looking at the SecurityBundle configuration setup it was clear that there wasn’t any options to have it clear all session attributes on switch user.  At this point it was clear I needed to use an event listener as the firewall dispatched the SwitchUserEvent when a user successfully switched user.  Below is an excerpt from my services.yml
This makes it so that it will call the following code on a successful impersonation of a user:

It’s as simple as that, you can get the actual user by calling $event->getTargetUser(). Long story short, the session can have some tainted values when using switch user as all attributes are not cleared.