Using the Hybrid Carbon image package in themes

A vintage camera sitting on leather alongside a pair of glasses and a magnifying glass.

Hybrid Carbon is a script for better handling of featured images in core WordPress. It provides more advanced controls and options. It also supports WordPress 5.0’s editor (Gutenberg) out of the box when necessary.

The primary goal of Hybrid Carbon is to find an image associated with a post in some way. Core WordPress has the Post Thumbnail API (featured images) for handling this. However, it doesn’t always cover our needs.

This is an overhaul of the original Get the Image script. So, if you were previously packaging it with your themes, you’ll want to update. I decided to start from scratch with a new vision that focused solely on an OOP approach to featured images. Get the Image had gotten a bit unruly and hard to maintain.

In this post, I’m going to cover how to integrate Hybrid Carbon into your themes and use its features.

Installation

You must have Composer installed on your system. You’ll need that if you want to install PHP packages.

First, navigate to your theme folder via the command line utility on your computer:

cd path/to/wp-content/themes/<your-theme-name>

Then, use Composer to install the package.

composer require justintadlock/hybrid-carbon

If you’re already loading the Composer autoloader file, you’re finished with installation (the Mythic starter theme does this). If not, you’ll need to add the following to your theme’s functions.php file.

if ( file_exists( get_parent_theme_file_path( 'vendor/autoload.php' ) ) ) {
    require_once( get_parent_theme_file_path( 'vendor/autoload.php' ) );
}

Basic usage

Most theme authors will only ever need to use the Hybrid\Carbon\Image static class, which is essentially syntantic sugar, for easy output of images. A basic call to display the featured image would look like the following.

Hybrid\Carbon\Image::display( 'featured' );

That will give you the same result as calling the core WordPress the_post_thumbnail() function. That’s the starting point. Of course, you’ll want to dive in a bit deeper than that.

Configuration

The Image::display() method accepts two parameters:

Hybrid\Carbon\Image::display( $type, array $args = [] );

$type parameter

The $type parameter accepts a string of a single type or an array of types. A type is the method used to locate an image. The following are the built-in types.

  • featured – This is the normal featured/thumbnail image.
  • attached – Searches for the first image attached to a post.
  • meta – Searches for an image attachment ID assigned to a custom meta field. This must be coupled with a meta_key set in $args (see below).
  • scan – Scans the post content for image attachment IDs in the HTML.

If passing in an array of types, the script will search for images in the order that you add them.

$args parameter

The $args parameter is an optional array of arguments to customize the output of the image.

  • post_id – ID of the post to get the image for (defaults to current post).
  • size – Size of the image to get. Defaults to post-thumbnail if size is set by theme. Otherwise, defaults to thumbnail.
  • meta_key – String or array of meta keys to search for (value must be an attachment ID).
  • min_width – Minimum width required to display the image.
  • min_height – Minimum height required to display the image.
  • attr – Array of HTML image attributes.
  • class – Class applied to the image. Defaults to entry__image.
  • link – Whether to link to the post. Defaults to false.
  • link_class – Class applied to the link. Defaults to entry__image-link.
  • caption – Whether to include captions for images that have them. Defaults to false.
  • before – HTML string to add before the output of the image.
  • after – HTML string to add after the output of the image.

Static class methods

The following methods are available for the Hybrid\Carbon\Image class.

// Returns an instance of the Hybrid\Carbon\Carbon class.
Image::carbon( $type, array $args = [] );

// Returns an instance of the Hybrid\Carbon\Carbon class after running its make() method.
Image::make( $type, array $args = [] );

// Returns an instance of the found Hybrid\Carbon\Contracts\Image object or false.
Image::image( $type, array $args = [] );

// Displays the HTML output of the image if one is found.
Image::display( $type, array $args = [] );

// Returns the HTML string of the image if one is found.
Image::render( $type, array $args = [] );

Example uses

The following are some examples of how to mix and match parameters for different scenarios.

Scan for images

Let’s suppose you wanted to see if a user has assigned a featured image and display it. However, you want to check if an image is available in the post content as a fallback. This is easy to do with the following code.

Hybrid\Carbon\Image::display( [
    'featured',
    'scan'
] );

Get image by custom meta

Sometimes you have an extra featured-type image. For example, I do this with my Plugin Developer plugin where I have both a “banner” image and an “icon” image. The plugin stores the image attachment ID as metadata for both of these. Hybrid Carbon handles this perfectly. All I need to know is the meta key.

Hybrid\Carbon\Image::display( 'meta', [
    'meta_key' => 'banner'
] );

Conditional display

In some theme designs, I only want to display an image if it meets certain minimum dimensions. Otherwise, it doesn’t look good with the design. The min_width and min_height options are great for this. You can use one or both of these, depending on the scenario.

Most likely, you’ll want to pass in a custom size that you’ve registered via add_image_size() too.

Hybrid\Carbon\Image::display( 'featured', [
    'size'       => 'themeslug-medium',
    'min_width'  => 600,
    'min_height' => 300
] );

Advanced usage

At times, you may need the image object itself. Feel free to check out the Hybrid\Carbon\Contracts\Image interface, which has the following public functions.

  • display() – Displays the image HTML output.
  • render() – Returns the image HTML.
  • src() – Returns the image source URI.
  • width() – Returns the image width.
  • height() – Returns the image height.
  • alt() – Returns the image alternative text.
  • caption() – Returns the image caption.

You can access this object via the Hybrid\Carbon\Image::image() method to roll out custom HTML output, for example.

<?php if ( $image = Hybrid\Carbon\Image::image() ) : ?>

    <div class="featured">
        <?php printf(
            '<img class="featured__image" src="%s" width="%s" height="%s" alt="%s" />',
            esc_attr( $image->src() ),
            esc_attr( $image->width() ),
            esc_attr( $image->height() ),
            esc_attr( $image->alt() )
        ) ?>
    </div>

<?php endif ?>

Of course, that’s a basic example of how you could work with the image object. It’d probably come in handy a bit more for things like slideshows and such.

Custom types

If you’re feeling super adventurous, you can roll custom types/methods for searching for images (see $type parameter above).

There are 4 “types” of image location methods that exist out of the box. These are:

  • attached
  • featured
  • meta
  • scan

You can build your own by extending the Hybrid\Carbon\Types\Base class like so:

namespace YourNamespace;

use Hybrid\Carbon\Types\Base;

class CustomType extends Base {
    // Overload methods from parent class here.
}

Then, you merely need to register your custom type:

add_filter( 'hybrid/carbon/types', function( $types ) {

    $types['custom-type-slug'] = \YourNamespace\CustomType::class;

    return $types;
} );

All of Hybrid Carbon is actually extendable like this. Custom type classes are the most likely use case, so I wanted to cover the basics of doing that. However, nothing is off-limits. You’re free to sub-class anything and change things to your liking.

Better featured images

Hybrid Carbon is a relatively lightweight wrapper over the existing APIs for handling media in WordPress. As I rewrote this package from the original Get the Image script, I knew I wanted to get back to the basics and implement things that I actually needed in most theme projects. However, I wanted it flexible enough so that I could extend it when a project calls for something custom. I feel like I’ve managed to find a good balance.

I’ll likely continue rolling out features for this in the future. There’s always more cool things that can be done with featured images.

Leave a Reply

Your email address will not be published. Required fields are marked *