WordPress custom post type code enhancements - Robert DeVore

Enhance the power of your WordPress Custom Post Types

I’ve been working on extending the WP Dispensary plugin and wanted to share some of the ways I’ve found to help boost the power of the Custom Post Types you create.

Custom Post Types are a great building block for turning WordPress into more than a piece of blogging software.

Going beyond the original Posts and Pages, you can now segment your content as much as you need, with relative ease.

I personally feel that WordPress wouldn’t be where it is today without the inclusion of Post Type’s in version 3.0.

This is my attempt to show how a few simple code snippets can push the boundaries of what’s possible with WordPress and Custom Post Types.

Plus, it’s a good way for me to keep the codes together in one place to reference in the future ?

If you’re new to CPT’s and/or haven’t built a Custom Post Type yet, you can check out this article from Torque that breaks CPT’s down and gives you a variety of ways to create your own.

Read it?

Got your own already built?

Great!

Let’s look at what we can do now that we have our CPT built.

Note: This article assumes you have a basic understanding of developing for WordPress. Please leave a comment or reach out on Twitter if you need further clarification on any of the tips below.

1. Custom API endpoints

Since this plugin seems like a likely candidate for future app integration, I want to add in some custom API endpoints to allow for content handling in something like AngularJS or vue.js.

Giving your featured image an API endpoint

You can add a function like the one below, adding a filter to rest_prepare_$CPTNAME which will grab the url for the Custom Post Type’s post featured image.

In the example below, I want to add the featured image endpoint to my Flowers CPT, so it’s rest_prepare_flowers.

/**
 * Adding featured image URL's to Flowers Custom Post Type
 *
 * @access public
 *
 * @param object  $data
 * @param WP_Post $post    The WordPress post object.
 * @param null    $request Unused.
 *
 * @return object The featured image data.
 */
function flowers_featuredimage( $data, $post, $request ) {
    $_data = $data->data;
    $thumbnail_id = get_post_thumbnail_id( $post->ID );
    $thumbnail = wp_get_attachment_image_src( $thumbnail_id, 'full' );
    $_data['featured_image_url'] = $thumbnail[0];
    $data->data = $_data;
    return $data;
}
add_filter( 'rest_prepare_flowers', 'flowers_featuredimage', 10, 3 );

Adding API endpoints for custom post_tag taxonomies

With WPD I have a variety of custom taxonomies for the CPT’s I created, so I wanted to make sure that data is available via API endpoints too.

The code I use to accomplish this is below.

/**
 * Add Flavor taxonomy for the Flowers Custom Post Type
 */
function flowers_flavor( $data, $post, $request ) {
    $_data = $data->data;
    $_data['flavors'] = get_the_term_list( $post->ID, 'flavor', '', ' ', '' );
    $data->data = $_data;
    return $data;
}
add_filter( 'rest_prepare_flowers', 'flowers_flavor', 10, 3 );

Adding API endpoints for custom category taxonomies

The same set up can work for your custom category taxonomies too.

/**
 * Add Category taxonomy for the Concentrates Custom Post Type
 */
function concentrates_category( $data, $post, $request ) {
    $_data = $data->data;
    $_data['concentrates_category'] = get_the_term_list( $post->ID, 'concentrates_category', '', ' ', '' );
    $data->data = $_data;
    return $data;
}
add_filter( 'rest_prepare_concentrates', 'concentrates_category', 10, 3 );

Adding custom API endpoints for your metabox data

When you create custom post types, a lot of times you find yourself adding in custom metaboxes to suppor the data you need users to control through your Custom Post Type.

This data can have a custom API endpoint created by using the following code snippet.

The $productsizes array are the metabox information I needed for pricing in the WPD plugin so your set up may vary based on your metaboxes.

/**
 * This adds the wpdispensary_prices metafields to the
 * API callback for flowers
 *
 * @since    1.1.0
 */
add_action( 'rest_api_init', 'slug_register_prices' );
/**
 * Registering Prices
 */
function slug_register_prices() {
    $productsizes = array( '_halfgram', '_gram', '_eighth', '_quarter', '_halfounce', '_ounce' );
    foreach ( $productsizes as $size ) {
        register_rest_field(
            array( 'flowers' ),
            $size,
            array(
                'get_callback'    => 'slug_get_prices',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    } /** /foreach */
}
/**
 * Get Prices
 */
function slug_get_prices( $object, $field_name, $request ) {
    return get_post_meta( $object['id'], $field_name, true );
}

Once you have your custom post types, taxonomies and metaboxes API endpoints added, you can now allow developers to consume your API data and have more control over how the data gets displayed.

Custom API endpoints in action

You can look at an example of each of these endpoints being added into a live API by checking out the CannaBiz demo here.

2. oEmbed improvements

With WP Dispensary I wanted to customize the output of information through the Embeds so that the custom data I display within WPD’s single item view gets embedded as well.

The filter below will filter out the_excerpt and replace it with the_content, making sure any content you added into the output of the_content get’s displayed properly.

/**
 * Returns the custom excerpt for oEmbeds.
 *
 * @since 1.0
 * @param  string $output Default embed output.
 * @return string         Customize embed output.
 */
add_filter( 'the_excerpt_embed', 'get_excerpt_embed' );
function get_excerpt_embed( $output ) {
    return the_content();
    return $output;
}
add_filter('embed_oembed_html', 'my_embed_oembed_html', 99, 4);
function my_embed_oembed_html($html, $url, $attr, $post_id) {
  return '<div id="wpd-oembed-wrap">' . $html . '</div>';
}

Note that on line 15 there is the wpd-oembed-wrap ID, which you can change to anything you’d like and then add custom CSS to the public output of your plugin.

+/**
 + * Register WP Dispensary's oEmbed stylesheet
 + */
 +function wpd_oembed_styles() {
 +
 +    wp_register_style( 'wpd-oembed', plugin_dir_url( __FILE__ ) . 'css/wp-dispensary-oembed.css', false, $this-version );
 +    wp_enqueue_style( 'wpd-oembed' );
 +
 +}
 +add_action( 'enqueue_embed_scripts', 'wpd_oembed_styles' );

See how I handle adding this in with WP Dispensary here.

Below is an example of how the WP Dispensary items get displayed through oEmbed now.

https://www.wpdispensary.com/demo/flowers/chemdawg/

3. Flush rewrite rules during your plugin’s activation

One thing that I looked over when building the earlier versions of the WPD plugin was flush_rewrite_rules.

If I’m being completely honest, at the time I didn’t even know it existed, so I was telling people in a FAQ page how to manually go in and resave their permalinks settings.

We live and learn, right? ?

Thankfully, WordPress does have a page in the codex on flush rewrite rules to look through.

With the code below, I am able to take the Custom Post Type function and add it to the activation hook within the WPD plugin.

I also do the same for the custom tag and category taxonomies for each menu type.

class WP_Dispensary_Activator {
    /**
     * Short Description. (use period)
     *
     * Long Description.
     *
     * @since  1.0.0
     * @access public
     *
     * @global $wp_rewrite
     *
     * @return void
     */
    public static function activate() {
        /**
         * Custom Post Types
         */
        wpdispensary_flowers();
        wpdispensary_edibles();
        wpdispensary_concentrates();
        wpdispensary_prerolls();
        wpdispensary_topicals();
        wpdispensary_growers();
        /**
         * Taxonomies
         */
        wpdispensary_aroma();
        wpdispensary_flavor();
        wpdispensary_effect();
        wpdispensary_symptom();
        wpdispensary_condition();
        wpdispensary_ingredient();
        /**
         * Custom Categories
         */
        wpdispensary_flowercategory();
        wpdispensary_ediblecategory();
        wpdispensary_concentratecategory();
        wpdispensary_topicalcategory();
        wpdispensary_growerscategory();
        /**
         * Flush Rewrite Rules
         */
         global $wp_rewrite;
         $wp_rewrite->init();
         $wp_rewrite->flush_rules();
    }
}

Now any time someone activates your plugin, your custom post types and taxonomies will flush and work with your current permalink settings.

Additional resources

Now that we’ve gone over a few ways to enhance your CPT’s, it’s time to dig even further and see what else you can do to make your plugins better.

Here’s some links to other content that you can check out, written by people much smarter than I am ?

Comments

2 responses to “Enhance the power of your WordPress Custom Post Types”

Leave a Reply

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