Adding Custom Aggregation Meta Boxes

Hello there! In today’s world, news aggregation sites are becoming more and more popular. So, what if you or your client want to get in on that action, but you don’t know how to make it easy. Well, worry no more! It’s actually fairly easy to do via the block editor. In today’s blog post, we’ll add a custom meta box in the Gutenberg editor, which will save a URL, and then filter our permalinks to use that URL if it exists.

Let’s dig in!

Adding a Meta Box

First thing’s first, we have to register our meta box. We can do that in our theme’s functions.php file, like so:

/**
Add External Link Meta Box
**/
function dvlpment_external_link_meta() {
    // Register the meta.
    register_meta('post', 'dvlpment_external_link_field', array(
        'show_in_rest'    => true,
        'single'          => true,
        'type'            => 'string',
    ));
}
add_action('init', 'dvlpment_external_link_meta');

This is fairly straight forward. We’re registering the meta and initializing it when WordPress loads, but before headers are sent.

Creating Our JS File

Next, we need to whip up a JS file that creates our Gutenberg block. To do that, I created a file under a folder titled JS, but it’s up to you where you place it!

(function(wp) {
    // Set up our variables.
    var el      = wp.element.createElement;
    var type    = wp.blocks.registerBlockType;
    var cont    = wp.components.TextControl;

    // Register the block type.
    type('dvlpment/meta-block', {
        title:      'External Link',
        icon:       'share',
        category:   'common',

        attributes: {
            blockValue: {
                type:       'string',
                source:     'meta',
                meta:       'dvlpment_external_link_field'
            }
        },

        edit: function(props) {
            var className       = props.className;
            var setAttributes   = props.setAttributes;

            function updateBlockValue(blockValue) {
                setAttributes({blockValue});
            }

            return el(
                'div',
                {className: className},
                el(cont, {
                    label:      'External Link Field',
                    value:      props.attributes.blockValue,
                    onChange:   updateBlockValue
                })
            );
        },

        save: function() {
            return null;
        }
    });
})(window.wp);

Now we have our code that’ll register our block type and save our data. Which means we now have to…

Enqueue Our JavaScript

Note that this mirrors normal enqueueing, but is slightly different. Also note that in our JavaScript file, we’re using wp-blocks, wp-elements, and wp-components, so those dependencies need to load before our JavaScript file tries to load.

/**
Enqueue Gutenberg Script
**/
function dvlpment_enqueue_scripts() {
	// Enqueue the script.
	wp_enqueue_script('dvlpment-meta-script', get_template_directory_uri().'/js/dvlpment-meta.js', array('wp-blocks', 'wp-element', 'wp-components'));
}
add_action('enqueue_block_editor_assets', 'dvlpment_enqueue_scripts');

Now, if you load up a post, you’ll see our custom meta box available and ready to use! But, how do we get it functioning? Well, we’ll do that via a filter.

Filter the Permalink

Since we have our meta, we’re going to tap into the post_link hook using a filter, so that we can get our field going!

/**
Replace Permalink
**/
function dvlpment_replace_permalink($link, $post) {
	//Get the link.
	$url = get_post_meta($post->ID, 'dvlpment_external_link_field', true);

	// Check if the URL is valid.
	$url = esc_url(filter_var($url, FILTER_VALIDATE_URL));

	// Return the new URL, if all is well.
	return $url ? $url : $link;
}
add_filter('post_link', 'dvlpment_replace_permalink', 10, 2);

Conclusion

And now you’re up and running! So you and your clients can aggregate like crazy because it’ll be easy.

Leave a Reply

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