Fortune Cookies Demo Page
The Fortune Cookie plugin is a WordPress version of the old Unix fortune cookie program that gives you a quotation or an aphorism (sometimes silly, occasionally rude or irreverent). The plugin stores quotations in a custom MySQL table, and uses the WordPress REST API to retrieve information from the backend.
The cookie shortcode inserts a cookie on a page. There are three optional arguments for the shortcode:
- idlist: a CSV list of IDs from the database entries. This overrides any other filters. If you supply a single ID, that entry will be returned every time. If you supply a list of IDs, then a single entry will be randomly chosen from that list.
- type: restricts the choice to a single type. Defaults to ‘quote’, and the sample cookies file also uses type ‘aphorism’.
- again: the value is either ‘yes’ (the default) or ‘no’. If the value is ‘yes’, then an Again button will be placed in the cookie.
Fortune Cookie ExamplesFor the 3 examples here, the first selects a random cookie. For the second, it selects a random cookie from among the specified IDs. The third randomly chooses a cookie of type ‘Aphorism. [cookie] [cookie idlist=”1,2,3,4,5,6,7,8,9,10,11,12″] [cookie type=’aphorism’]
The AGAIN buttons request a cookie using the WP REST API, which returns a JSON object with a matching fortune cookie. The callback function ProcessNewCookie inserts the HTML into the page based on the specified selector. The plugin includes a couple of backend pages (see below) for importing and managing the fortune cookies.
I’ve initially defined two types of cookies (‘Quote’ and ‘Aphorism’), and I built an import mechanism that reads a text file of fortune cookies and stores them in a table in the WordPress database. The rendering function that creates the HTML for a given cookie is determined by the type, so you could easily add a new type or change the rendering function for an existing type.
Backend Administration of the Plugin
After activating the plugin, the WordPress dashboard has a new top-level entry called “Fortune Cookie Settings” with 2 subpages. You can import, view, and edit cookies.
- The Settings and Import page lets you import cookies from a data file located in the plugin folder (or a subdirectory of the plugin folder).
- The Fortune Cookies page lists all of the defined cookies in the custom table, and allows you to Edit, Clone, or Delete any given entry. This list is paginated — if you import the sample data file, you’ll get almost a thousand entries. You can define the number of entries to see on each page in the previous Settings and Import page.