Adam Cap

  • About
  • Mail
  • Archive/Search

PHP

code | Language … see also: command line / CSS / JavaScript / HTML

Save Jetpack “Site Stats” Pageviews as Post Meta

↘︎ Jan 30, 2019⇠ | skip ⇢

A website that pulls decent traffic may want to display the number of views each of its pages has gotten. This information can make a website seem more active or credible (or, generally, worthwhile perusing) than it would otherwise to a visitor. This datum can also subtly and meaningfully guide a user’s interactions with a website (i.e., a page with more views is likely worth visiting in preference to a page with less views). YouTube, for example, leverages view counts to (and which) influence whether a video may be worth watching.

WordPress doesn’t track pageviews out of the box, but Jetpack is a popular plugin, which many WordPress websites use, that does track pageviews. It does not save pageviews, however, in a way which makes this data readily available to plugin or theme developers. But it is possible to import Jetpack’s pageviews so that the data is useable. And it makes sense to piggyback off Jetpack’s stats, rather than devise a unique solution to track pageviews; such inventions are typically unstable, imprecise, or prone to bogging down performance. Holding hands with Jetpack is a pretty sure-fire solution which adds minimal overhead (and elegance, too).

How It Works / The Approach

The data that Jetpack collects is available through the WordPress.com Stats API which can be accessed with the stats_get_csv function provided by Jetpack. This API can be called while a page is loading, i.e., before the page is displayed to the visitor (in the wp_footer action, for example), but a better method is to call the API after the page has finished loading, via Ajax. An Ajax implementation allows the user to visit the page unimpeded—without waiting for the API request to process first, which may take a split second or two—a relative eternity in the context of the internet (where instantaneous responses are generally expected). Instead, the call happens in the background, after the page has loaded, which affords the user a better experience.

The Code (Action!)

First, load a JavaScript file to trigger an Ajax request:

This is the JavaScript file—place it in the correct path (defined by wp_enqueue_script above):

Finally, process the Ajax request (triggered by the JavaScript above):

Combined, this code will:

  1. save the pageviews for each post
  2. in post meta key views
  3. every ~4 hours.

This data can be displayed with get_post_meta and posts can be sorted by views, e.g., to query for popular posts:

Hacking “days”

The WordPress.com Stats API caches requests. This is problematic for us, because it means that a page’s current view count may not be returned for our request; we could instead be provided a view count from days ago. Typically, -1 is supplied for the days parameter, in this API call, to return “total views” (views accumulated in the past “infinite” [or all] days). However, the results from 'days' => -1 cache for an indeterminate amount of time, and thus will not always be current when requested.

To work around this, we attempt to bust the cache with each call, by requesting a page’s view count from the past X days (instead of -1 days), where X is a random number from 36,500 to 2,147,483,647.

The former figure I chose somewhat arbitrarily; it is roughly 100 years in days. (I figure WordPress will be history by that point.) The latter figure comes from PHP’s getrandmax function.

This range has proven sufficient—for me, anyway—to reliably bust the Stats cache with each API request.

Me

circa 2008 (20 y/o)

about adam

Jump…

  • 19 Jan 30: Save Jetpack "Site Stats" Pageviews as Post Meta #JavaScript #PHP #WordPress
  • 19 Jan 18: Add Partner/Associates/Tracking ID/Tag to Amazon Links #PHP #regex #WordPress
  • 19 Jan 18: Add Fancybox Attribute to Image Links #PHP #regex #WordPress
  • 19 Jan 18: Automatically Bold (or Style) the First X Words of Content #PHP #regex #WordPress
  • 19 Jan 15: Add Media/Attachment Source Fields (and Display Image Sources in Content) #PHP #regex #WordPress
  • 19 Jan 7: Remove Nonbreaking Spaces ( 's) from Content and Text Widgets #PHP #WordPress

More…
WordPress (Tag) / code (Post Type)

Add Partner/Associates/Tracking ID/Tag to Amazon Links

↘︎ Jan 18, 2019⇠ | skip ⇢

Many websites link to products on Amazon, this one included, in hopes of capturing commission from Amazon’s affiliate program. In order to be credited with the sales generated through their promotional efforts, the affiliate needs to affix a tracking ID (or tag; the verbiage varies) onto their links, like so:

  • https://www.amazon.com/
  • https://www.amazon.com/?tag=adamcapr-20

Here are a couple of options to automatically tag Amazon links, within post content, with a specified tracking ID, using regular expressions.

v1: Raw

This first version will indiscriminately add a tracking tag to (or replace an existing one on) any amazon.com URLs:

v2: Clean

This second version extracts ASINs from amazon.com/dp/ URLs, then rewrites those URLs, so that extraneous strings and parameters are stripped before adding the tracking tag. Other, non-/dp/ amazon.com URLs will have the tracking tag assimilated in the manner above.

The advantage to implementing automation like this is that it lessens cognitive demands for precision and thus can expedite publishing processes.

Of course, it’s probably more prudent to curate Amazon short links (e.g., https://amzn.to/2Mkz6k2) which are less susceptible to the type of manipulations performed above. Web browsers and other services can more easily hijack full links, diverting revenue away from those who instituted them.

Me

circa 2009 (21 y/o)

Popularly…

  • 19 Jan 18: Fix Line Height for Input Placeholders in Safari #CSS
  • 19 May 4: Prevent iOS + WordPress from Replacing Arrows (and Other HTML Symbols) with Emoji #CSS #HTML
  • 19 Jan 30: Save Jetpack “Site Stats” Pageviews as Post Meta #JavaScript #PHP #WordPress
  • 19 Jan 18: Add Partner/Associates/Tracking ID/Tag to Amazon Links #PHP #regex #WordPress
  • 19 Jan 16: Move from Local macOS Development Sandbox (MAMP) to Live Production Environment #command line #WordPress
  • 19 Jan 26: Use Git to Manage WordPress Projects Developed Locally on macOS #command line #WordPress
  • 19 Mar 23: Move from Live Production Environment to Local macOS Development Sandbox (MAMP) #command line #WordPress
  • 19 Jan 15: Add Media/Attachment Source Fields (and Display Image Sources in Content) #PHP #regex #WordPress
  • 19 Jan 18: Add Fancybox Attribute to Image Links #PHP #regex #WordPress
  • 19 Jan 7: Remove Nonbreaking Spaces ( ’s) from Content and Text Widgets #PHP #WordPress
  • 19 Jan 18: Automatically Bold (or Style) the First X Words of Content #PHP #regex #WordPress

More…
regex (Tag) / WordPress (Tag) / code (Post Type)

Add Fancybox Attribute to Image Links

↘︎ Jan 18, 2019⇠ | skip ⇢

Fancybox is my lightbox script of choice. I feel it improves the end-user’s web-browsing experience, so I use it in most projects.

To enable Fancybox on an image, it’s necessary to:

  1. Surround the <img> element with a link that points to an image file.
  2. Add a data-fancybox attribute (and optional group declaration) to the link.

Typically, you’ll be including the hyperlink along with the image when you insert it through the WordPress post editor. This code will automatically add the still-needed Fancybox attribute for you:

Other lightbox scripts are enabled similarly; this code is adaptable.

Me

circa 2017 (29 y/o)

Randomly…

  • 19 Jan 18: Automatically Bold (or Style) the First X Words of Content #PHP #regex #WordPress
  • 19 Mar 23: Move from Live Production Environment to Local macOS Development Sandbox (MAMP) #command line #WordPress
  • 19 Jan 15: Add Media/Attachment Source Fields (and Display Image Sources in Content) #PHP #regex #WordPress
  • 19 Jan 18: Add Fancybox Attribute to Image Links #PHP #regex #WordPress
  • 19 May 4: Prevent iOS + WordPress from Replacing Arrows (and Other HTML Symbols) with Emoji #CSS #HTML
  • 19 Jan 18: Add Partner/Associates/Tracking ID/Tag to Amazon Links #PHP #regex #WordPress
  • 19 Jan 16: Move from Local macOS Development Sandbox (MAMP) to Live Production Environment #command line #WordPress
  • 19 Jan 26: Use Git to Manage WordPress Projects Developed Locally on macOS #command line #WordPress
  • 19 Jan 7: Remove Nonbreaking Spaces (&nbsp;’s) from Content and Text Widgets #PHP #WordPress
  • 19 Jan 18: Fix Line Height for Input Placeholders in Safari #CSS
  • 19 Jan 30: Save Jetpack “Site Stats” Pageviews as Post Meta #JavaScript #PHP #WordPress

More…
regex (Tag) / WordPress (Tag) / code (Post Type)

Automatically Bold (or Style) the First X Words of Content

↘︎ Jan 18, 2019⇠ | skip ⇢

I first noticed the usage of lede styling on Wired.com, which styling, at least in Wired’s implementation, is where the first three words of a news story are styled differently that the rest of the piece, to attract the wandering eye’s attention. (“Reader: Start here!”) The concept is similar in principle to that of the drop cap, which has been used in print for centuries.

I wanted to apply similar styling to the content on my website, but I didn’t want to go through every post I’ve ever written to add the necessary HTML—a <span> element with an arbitrary class name around the first three (or however many) words of a post. So, instead, I wrote this content filter to do it automatically:

With the markup in place, the text can be styled as so:

It will likely be possible to achieve this targeted styling with CSS alone sometime in the future—through an `::nth-word()`-esque pseudo element, without HTML markup—but for now, this solution affords an immediate response and flexibility.

The number of lede words can be controlled through a custom field—here I use the meta key _lede_words—and I’m partial to solutions like Carbon Fields or CMB2 to assist with the selection. Here’s the corresponding metabox for Carbon Fields that I’ve created:

Note: If any of the lede words are hyperlinked, the above regex will fail. Manually add markup in those odd scenarios, or attempt to amend the code.

Me

circa 2013 (25 y/o)

More…
regex (Tag) / WordPress (Tag) / code (Post Type)

Add Media/Attachment Source Fields (and Display Image Sources in Content)

↗︎ Jan 19, 2019⇠ | skip ⇢

WordPress doesn’t ship with a deliberate method for keeping track of where attachments have come from. You can toss sources (names and URLs) into caption or description fields, but those fields are not intended to house that information, they are not conducive for displaying said information, and thus the average WordPress user never divulges the origins of their attachments/media.

Thankfully, attachment fields are readily extensible, and it’s easy to display attribution—with the right code!

First, the following will add Source URL and Source Name fields to the “Attachment Details” and “Edit Media” screens:

With these fields in place—and source info subsequently entered—attachments can be attributed in a variety of ways. Below are two examples for attributing images used within post content by means of affixing a source link to each image’s HTML markup.

For captioned images:

And non-captioned images:

Note: If the source name is excluded, the hostname will be extracted from the URL, and that will be displayed as the source link text. This allows you to consciously omit the source name, in most cases, to expedite data entry. The hostname is often sufficient for attribution (but not always; a source name should be specified for nearly all social media URLs, for example).

The next step is to style the source links so that they look agreeable within context. Here is the raw CSS I used for one project—which will need to be tweaked—to afford you a head start:

Finally, here’s a screencap of the finished product (image with source-link attribution in the bottom-right corner):

Attribution should be commonplace and easy, though it typically isn’t, and this implementation is at least one small ethical step forward.

Me

circa 1996 (9 y/o)

More…
regex (Tag) / WordPress (Tag) / code (Post Type)

Remove Nonbreaking Spaces (&nbsp;’s) from Content and Text Widgets

↗︎ Jan 18, 2019⇠ | skip ⇢

Nonbreaking spaces are all-too-often inadvertently inserted into TinyMCE rich-text content, which can cause awkward and unintended line breaks within paragraphs. These few lines of code annihilate the issue, on the frontend, by replacing nonbreaking spaces with normal, word, spacebar spaces:

\xc2\xa0 is the UTF-8-encoded nonbreaking space character (which resides in a WordPress database and is manipulable here).

For more on nonbreaking spaces, see Butterick’s Practical Typography.

Me

circa 2017 (29 y/o)

More…
WordPress (Tag) / code (Post Type)

  • Home
  • About
  • Archive
  • Mail
  • Random
  • Dingus
  • Reading
  • Code

ADAM CAP is an elastic waistband enthusiast, hammock admirer, and rare dingus collector hailing from Berwyn, Pennsylvania.

My main interests at this time include reading, walking, and learning how to do everything faster.

Psst: If you find my website helpful or enjoyable, please join my newsletter and/or send me an email—I want to hear from you!

Disclosure: As an Amazon Associate I earn from qualifying purchases.

© 2009–2023 Adam Cap(riola) top ⇡