Developers: discover Jetpack’s little secrets

in WordPress

You probably already know the Jetpack plugin. But did you know it included developer features you can use when building sites for your clients?

In this article we’ll discover some of Jetpack’s little secrets, and learn how to use them in our projects.

Another month, another #WPBudapest meetup! This month, I talked about Jetpack. The plugin is quite popular, and if you read this blog you probably heard about it already. ? Instead of introducing the plugin and its most useful modules, I decided to talk about some of Jetpack’s little secrets. While Jetpack includes quite a few useful modules, it also comes with tools that can make your life easier when creating new sites for your clients. Instead of reinventing the wheel, we’ll use Jetpack’s tools instead.

You can check my slides here, and a walk-through of my talk below.

Why use Jetpack

  • Jetpack includes 36 modules. Most of these modules provide all the basics you need when launching a new site.
  • Your clients might already know the plugin: they may have used it on a personal blog, on WordPress.com or on WordPress.org. They might have used some its functionalities in one of the mobile apps, or in the desktop app.
  • If your clients don’t know about it, you probably do. You know the plugin is maintained, and regularly updated. You know it’s developed in the open, on GitHub, and anyone can post there to report bugs or suggest new features.
  • If you’re not familiar with the plugin yet, other developers are: a simple Google Search will help you find posts, forum threads, and plugins where others have leveraged some of the features included in Jetpack.
  • Jetpack also comes with free support. A support team is there to answer all your questions in the WordPress.org forums or via email.
  • And well… It’s free ?

Before we get started

In the examples below, we’ll leverage Jetpack features in our own plugins and themes. When doing that, you’ll want to make sure nothing breaks if your client ever decides to deactivate Jetpack.

We’ll consequently use functions_exists() and add_theme_support() (#) in all the examples below. add_theme_support() is interesting because it handles fallback for you. If the functionality you’re trying to add to the site can’t be found, nothing will break.

You will also need a few additional resources:

I would also recommend carefully considering 2 things:

  • Are the features you’re adding linked to the site’s design, or to its content? If you’re working on a feature that will remain once the user switches to a different theme, you’ll want to add all your code to a separate plugin, or to a functionality plugin.
  • Create 2 separate accounts on the site, and on WordPress.com: one for you, one for your client. Thus, once you’re done developing the new site, you can transfer all Jetpack ownership to your client, and keep your own account to monitor the site later, thanks to Jetpack Manage.

Let’s clean things up before we begin

Remove modules from Jetpack

As I mentioned earlier, Jetpack includes 36 different modules. You probably love some of those, but there are also a few that you don’t use, and even a few that you’ll never use. It could be because you already developed or integrated that feature in another plugin, for example.

Jetpack includes a management interface so you can deactivate what you don’t need. Once a module is deactivated, its code won’t run on the site. Careful though: any admin on the site has access to Jetpack settings, and can activate a module you previously deactivated.

If you’d rather restrict the number of modules available to your client, even if they’re an admin on the site, you can use the jetpack_get_available_modules filter to completely remove some modules from the Jetpack interface. That’s the safest and easiest way to ensure that your client will never activate those modules.

/**
 * Let's activate 7 specific modules, and nothing more.
 */
function jeherve_only_seven_modules( $modules, $min_version, $max_version ) {
    $my_modules = array(
        'stats',
        'photon',
        'related-posts',
        'markdown',
        'sso',
        'custom-content-types',
        'custom-css',
    );
    return array_intersect_key( $modules, array_flip( $my_modules ) );
}
add_filter( 'jetpack_get_available_modules', 'jeherve_only_seven_modules', 20, 3 );

This method is also a great way to pre-configure Jetpack, even before you’ve installed and activated the plugin on your site. To find out more, you can check one of my earlier posts.

Custom Content Types

Illustratr Theme

Custom Post Types can be very useful, but it’s often recommended that you leave them out of your themes, to make sure your client doesn’t lose any content if they ever decide to switch themes.

When appropriate, it can consequently be useful to use one of Jetpack’s CPTs: your client won’t lose the CPTs when switching themes, and you may leverage the work done by other theme authors.

Jetpack includes 4 different CPTs:

  • Portfolio
  • Testimonials
  • Menus (for a Restaurant site)
  • Comics

You can use add_theme_support() in your theme to declare support for one of these CPTs:

function jeherve_add_jetpack_portfolio() {
    add_theme_support( 'jetpack-portfolio' );
}
add_action( 'after_setup_theme', 'jeherve_add_jetpack_portfolio' );

Jetpack Custom Content Types Options

You are then free to create template pages for these CPTs in your theme, or use the shortcodes included in Jetpack to display CPT content anywhere in your posts or pages.

Site Logo

Jetpack Site Logo

WordPress already comes with built-in theme features allowing us to add a custom background, a custom header image, and a favicon. Custom Header Images are useful, but they’re often used as a background image in the header of a theme.

Jetpack allows you to add a new section to the customizer, that will allow you to define a custom logo. You can then display that logo anywhere on your theme, like on top of that background image in your header for example.

Even better, that logo will then be used in your site’s Open Graph Meta Tags if you use Jetpack’s OG tags.

To add support for that feature in your theme, you’ll use add_theme_support() once again, like so:

function jeherve_add_site_logo() {
    add_theme_support( 'site-logo', array(
        'size' => 'full',
    ) );
}

You can then display the logo wherever you want. Typically, it’s added in header.php:

if ( function_exists( 'jetpack_the_site_logo' ) ) {
    jetpack_the_site_logo();
}

Warning: that feature will most likely be added to WordPress core in WordPress 4.5, so you might not even have to use Jetpack in the future. See this trac ticket to find out more.

Responsive Videos

Jetpack Responsive Videos

If you work on sites that embed videos, you probably already know FitVids, a jQuery plugin you can add to your theme to resize all videos on mobile devices.

Instead of adding that library to your theme, you could use Jetpack! It bundles its own library, that’s a bit lighter and more adapted to the videos you may add to a WordPress site.

To add support, add the following to your theme:

function jeherve_add_responsive_videos() {
    add_theme_support( 'jetpack-responsive-videos' );
}

Breadcrumbs

Jetpack Breadcrumbs

Do I really need to explain what it is? ? This Jetpack tool is simple, and can be used anywhere in your theme:

if ( function_exists( 'jetpack_breadcrumbs' ) ) : ?>
    <div class="my-breadcrumbs">
        <?php jetpack_breadcrumbs(); ?>
    </div><!-- .my-breadcrumbs -->
<?php endif; ?>

Markdown

Markdown is a really useful language if you write a lot. It’s not for everyone, but if you’re familiar with it it could be really useful in your projects! Jetpack bundles a Markdown processing library that’s used in the post editor, but that you could also use in your own code.

It could for example come in handy if you usually deliver a user guide, or some tutorials to your clients alongside the site you developed for them. Instead of writing these 10 pages in HTML, you could write everything in Markdown, and use Jetpack to transform that Markdown into HTML for you. You could then embed the result in a new page inside your client’s dashboard.

if (
    class_exists( 'Jetpack' ) &&
    Jetpack::is_module_active( 'markdown' )
) {
    jetpack_require_lib( 'markdown' );
 
    $text_md = WPCom_Markdown::get_instance()->transform(
        $original_text,
        array(
            'id'      => false,
            'unslash' => false,
        )
    );
}

Photon

Watson

Photon is a free image CDN included in Jetpack. It also does a bit more than your regular CDN:

  • It optimizes, resizes, and caches several versions of your images, and serves the right image depending on the page and the device you’re on.
  • It serves the images your browser can support. For example, if you use Google Chrome, Photon will serve WebP images to your readers. That format can be 25% lighter than jpg, without any loss in quality.
  • Photon also comes with an API and filters that will allow you to generate images that fit your needs. Let’s explore some of the options below.

In the following example, we’ll use the jetpack_photon_pre_args to change the aspect of all the images on our site with one function:

  • First, we’ll enable lossy compression for the images. If you’re not a photographer, that’s a great way to improve your site’s performance.
  • We’ll remove all EXIF metadata from our images, to make them lighter. Careful though: some image editors and cameras store custom color profiles in EXIF metadata. If you remove EXIF from such images, the image’s aspect may change a lot.
  • We’ll display all our images in grayscale. While that’s probably not something you want to implement on every site, it has its advantages. ? For example, you could use that parameter to change all images in posts that use the vintage tag!
function jeherve_custom_photon( $args ) {
    $args['quality'] = 80;
    $args['strip']   = 'all';
    $args['filter']  = 'grayscale';
    return $args;
}
add_filter( 'jetpack_photon_pre_args', 'jeherve_custom_photon' );

Watson in black and white

Let’s now look at another example. You could use Photon to display images with very specific dimensions and cropping, on your theme’s home page:

Small Watson

if ( function_exists( 'jetpack_photon_url' ) ) {
    $args = array(
        'crop'   => '45,45,250px,250px',
    );
    echo jetpack_photon_url(
        esc_url( $image_url ),
        $args
    );
}

In the example above, we used Photon’s crop parameter. The 2 first values handle the cropping (45% from the bottom and the left of the original image), while the 2 last values handle the image’s dimensions (250x250px).

This jetpack_photon_url() can consequently be very useful in your themes.

SSO

Jetpack SSO

You can’t ignore your site’s security anymore. If your site uses WordPress, your login form will eventually be hammered by hackers and script kiddies. That’s obviously very bad if they manage to log in. It’s also bad for your server, as these repeated attempts take their toll on your site.

Luckily, some plugins are there to help you.

Jetpack and its Protect module is a good solution. But let’s consider another alternative: instead of using plugins to protect your log in form, why not let WordPress.com handle all log ins for you?

You can indeed remove all log in forms from your site and redirect everyone to WordPress.com, where the WordPress.com team will take care of everything.

To do so, we’ll need different filters:

add_filter( 'jetpack_remove_login_form', '__return_true', 9999 );
add_filter( 'jetpack_sso_bypass_login_forward_wpcom', '__return_true', 9999 );
add_filter( 'jetpack_sso_display_disclaimer', '__return_false', 9999 );
 
add_filter( 'wp_authenticate_user', function() {
    return new WP_Error( 'wpcom-required', “Pas de connection ici.” );
}, 9999 );
add_filter( 'allow_password_reset', '__return_false' );
 
// Force 2 factor authentication
add_filter( 'jetpack_sso_require_two_step', '__return_true' );

You can learn more about this method here.

Tonesque

Tonesque

Tonesque is another library bundled with Jetpack. Give it an image, and the library will generate 2 colors:

  • An average color based on 5 different points in the image.
  • A contrast color (black or white), based on the average color; if that average color was dark, Tonesque will return a white contrast color.

It’s a useful tool to change your site’s design based on each post’s Featured Image, for example. I actually use it on this very site, and in a plugin named Color Posts.

To use this feature, we’ll once again use add_theme_support():

function jeherve_add_tonesque() {
    add_theme_support( 'tonesque' );
}

We can then grab an image and have Tonesque generate the 2 colors for us:

if ( class_exists( 'Jetpack_PostImages' ) ) {
    $image = Jetpack_PostImages::get_image( $post_id );
    if ( ! empty( $image['src'] ) ) {
        $image = $image['src'];
    } else {
        $image = 'default_image.jpg';
    }
 
    $tonesque = new Tonesque( $image );
    $tonesque = array(
        'color'    => $tonesque->color(),
        'contrast' => $tonesque->contrast(),
    );
}

As you’ve probably noticed, I used another small Jetpack secret in the code above: the Jetpack_PostImages class can be used to grab an image for any post. It looks at all the ways you may have added an image to a post (Featured Image, Slideshow, Gallery, Attachments, or even images copied from other sites), and returns a representative image.

Now, I know what you’re going to say: “I’m not going to redesign my theme with only 2 colors. I need more!” No worries, Jetpack’s got you covered! ??

For the grand finale…

Create a color scheme using Tonesque, Sass, and Jetpack’s Custom CSS editor

Custom CSS

Jetpack includes a very handy Custom CSS module. A built-in editor in your dashboard allows you to add CSS, Sass, and Less to your site, without having to edit your theme stylesheet. In the example below, we’ll use the underlying libraries, in combination with Tonesque and the Jetpack_PostImages class I mentioned earlier.

  1. Jetpack_PostImages will grab a representative image from each post.
  2. Tonesque will generate an average color from that image.
  3. We’ll use Sass to create a color scheme based on that average color. We’ll play with hue, saturation, and lightness to generate several new colors. If you’re not familiar with Sass color functions, you can check this excellent tutorial here: Controlling color with Sass color functions.
  4. We’ll use all these colors in a Sass stylesheet, and customize different elements of our site.
  5. We’ll use Jetpack Custom CSS library to process the Sass into CSS, and minify that CSS.
  6. We’ll add that CSS to our site.
  7. Et voilà! ?

We’ve already covered 1) and 2) earlier. Here is how our Sass stylesheet will look like. As you can see, it all starts from $base-color, the average color we got from Tonesque:

/* Hue of our base color */
$base-hue: hue( $base-color );
 
/* Let's generate new colors using Sass's hsl */
$body-background: hsl( $base-hue, 0, 97% );
$text-color: hsl( $base-hue, 4%, 26% );
 
body {
    background: $body-background;
    color: $text-color;
}

We then add the color we got from Tonesque to the top of the stylesheet, and process / minify everything:

if ( class_exists( 'Jetpack_Custom_CSS' ) ) {
    $base_sass = file_get_contents( 'colors.scss' );
    $sass = '$base-color: #' . $color . '; ' . $base_sass;
 
    $css = Jetpack_Custom_CSS::minify( $sass, 'sass' );
}

Done! All we have left to do is to add that CSS to our theme!

Want a demo? Check the Umbra theme on WordPress.org.

That’s all for now! I hope this helped you discover some of Jetpack’s hidden secrets, and will inspire you to do more with the plugins you already use to create websites for your clients!