Half-Elf on Tech

Thoughts From a Professional Lesbian

Category: How To

  • CMB2: Conditional Meta Fields

    CMB2: Conditional Meta Fields

    Even though Gutenberg is on the rise, and every day gets us closer to using a whole new editor, we still use the ‘classic’ editor and we’re still beholden to it’s space limitations. I have strong feelings about how to properly utilize space when using CMB2, but not included in that specific post is this.

    Fields You Don’t (Always) Need

    There are three types of fields for CMB2.

    1. Fields you always need to use
    2. Fields that are optional
    3. Fields that are needed only in specific situations

    Most of the time we use option 2. Option 3 is the tricky one, though, since most of the time we end up having things show based on actions. That is, I save a post, and new options show up. When it comes to CMB2, we really don’t want to have to save and then edit and save and edit.

    Yuck!

    Thankfully this is all possible.

    Practical Example: Affiliates

    Today we’re making a box to handle affiliate links. There are three types of links: Amazon, Genric, and ‘Unique.’

    The Amazon one will link directly to a signup link and the generic one links to the same thing only on Click Junction. Both of those links will have affiliate details backed in so I don’t have to look them up later. This also means any partners I have on the site don’t need to know all the gory details. Bazinga.

    The last one, though ‘Unique’ is tricky. You see, when someone picks that, I want them to be able to put in a specific URL that may be affiliate linking somewhere else. But let’s start out with how it normally works.

    Make Your Fields

    function my_site_cmb2_metaboxes() {
    	// prefix for all custom fields
    	$prefix = 'my_sites_';
    
    	// Metabox Group: Must See
    	$cmb_affiliate = new_cmb2_box( array(
    		'id'           => 'affiliate_metabox',
    		'title'        => __( 'Affiliate Details', 'my-domain' ),
    		'object_types' => array( 'post_type_shows' ),
    		'show_in_rest' => true,
    	) );
    
    	// Field Box: Affiliate Type
    	$field_affiliatetype = $cmb_affiliate->add_field( array(
    		'name'             => __( 'Type', 'my-domain' ),
    		'id'               => $prefix . 'affiliate',
    		'type'             => 'select',
    		'options'          => array( 
    			'amazon'  => 'Amazon',
    			'generic' => 'Generic',
    			'url'     => 'Unique Link',
    		);
    		'show_option_none' => true,
    	) );
    	// Field Box: Affiliate Links
    	$field_affiliateurl = $cmb_affiliate->add_field( array(
    		'name'    => __( 'Link', 'my-domain' ),
    		'id'      => $prefix . 'affiliateurl',
    		'type'    => 'text_url',
    	) );
    );
    

    That’s pretty normal for CMB2 and looks like this:

    CMB2: Affiliate Details

    Normal, but … I want to hide that Link field unless a specific option is selected. Enter javascript.

    Hide That Field (Conditionally)

    Make a file for your javascript. I’ve called mine cmb2.js and put it in the same folder as my file that will enqueue the scripts.

    // Either create a new empty object, or work with the existing one.
    window.MySite_CMB2 = window.MySite_CMB2 || {};
    
    (function( window, document, $, app, undefined ) {
    	'use strict';
    
    	app.cache = function() {
    		app.$ = {};
    		app.$.select = $( document.getElementById( 'my_sites_affiliate' ) );
    		app.$.field = $( document.getElementById( 'my_sites_affiliateurl' ) );
    		app.$.field_container = app.$.field.closest( '.cmb-row');
    	};
    
    	app.init = function() {
    		app.cache();
    		app.$.select.on( 'change', function( event ) {
    			if ( 'url' === $(this).val() ) {
    				app.$.field_container.show();
    			} else {
    				app.$.field_container.hide();
    			}
    		} ).trigger( 'change' );
    	};
    
    	$( document ).ready( app.init );
    })( window, document, jQuery, MySite_CMB2 );
    

    And then call the enqueue, but only when appropriate (because we want to keep the load low):

    add_action( ‘admin_enqueue_scripts’, ‘my_site_admin_enqueue_scripts’ );

    function my_site_admin_enqueue_scripts( ) {
    $screen = get_current_screen();
    if ( ! isset( $screen->post_type ) || ‘post_type_shows’ !== $screen->post_type ) return;

    wp_enqueue_script( 'custom-js', plugins_url( '/cmb2.js' , __FILE__ ), array( 'jquery' ) );
    

    }

    And that works like this:

    GIF of how it shows and hides things

    A Word of Warning

    While all this is great for the sighted people, hiding things is not actually all that great for those who use screen-readers. For that you’d want to toggle the field to be disabled.

  • It’s Just Math

    It’s Just Math

    Recently I posted about how I added new features to a show scoring system, over on LezWatchTV. We added in what we call Intersectionality, which is rewarding shows for positive representation of diversity in the world. Naturally that begs the question of what is show scoring (answer: it’s calculative a qualitative value of how good a TV show on a scale of 0-100). And that makes people ask …

    How do you do that?

    It’s really math

    Look, the bare answer to all of this is that it’s math. I’m taking the meta data we assign to shows, like how much screen time characters get and how good the show is for them, and so on, and assigning numbers to those values. Then I add up the numbers, in various ways, and determine what the over all score is.

    It’s a little more complex than that, and if you’re super interested in how it all works, we wrote up an explanation as to the framework I created to value shows.

    But most people who ask me how I did this aren’t asking about the math, they want to know about the code. That is, how did I get WordPress to automate all this, because you know I don’t do it all by hand. No, I do it when the post saves.

    Magical Hooks

    Let’s take a moment. What’s a hook anyway?

    A hook is an action or a filter in WordPress, which allows you to write code that ‘hooks’ into the rest of WordPress code. You can use this to trigger your code to run at specific times.

    For example, if I had a hook called publish_post (which we do – WordPress has that built in), and I wanted to run my show calculations when I publish a post, I would do this:

    add_action ( 'publish_post', 'shows_calculations' );

    That would of course require me to have a function called show_calculations() that does the math, which is fine. But. I don’t want to do this on post publish. I want to do it on post save, and only if the post is of the shows post type. And that sounds like a lot of if/then statements until you learn about dynamic hooks.

    You see, I’m using the save_post_ hook, which runs when a post is saved, and it’s a little special. Unlike a hook like publish_post(), this hook lets me customize it how I want by being save_post_{$post->post_type} …

    Yeah those curly brackets are weird, right? That’s the dynamic part. That part changes.

    Dynamic Saving

    To understand how the hook name changes, you should know that in my case, I have a post type called post_type_shows — logical right? Well the subsequent hook is called save_post_post_type_shows — that is, I’ve replaced those weird brackets with the post type.

    Once you know your new hook name, it’s like every other hook:

    add_action( 'save_post_post_type_shows', 'shows_calculations', 10, 3 );

    What that does is call the function post_type_shows_calculations on every post save. And that function calls another one I called do_the_math() which passes the post ID to the myriad complications of calculations I perform.

    But the magic literally is in that post save hook.

  • NoEmbed: Embedding What’s Not oEmbed

    NoEmbed: Embedding What’s Not oEmbed

    We all love oEmbed with WordPress. Want to include a YouTube video? Paste in the URL and call it a day!

    The magic is that WordPress sends data to the YouTube oembed endpoint (i.e. a special app on YouTube that translates URLs to embed things) and says “Hi, I have this video URL here, what can I use to embed it?” And YouTube replies back “This javascript, my fine friend!” WordPress tips it hat and carries on, swapping the URL out for javascript on the fly.

    Awesome.

    Except when it doesn’t work because it can’t because there isn’t an oEmbed endpoint.

    What Now?

    Usually I make a shortcode. But my man Otto always grumbles and tells me to make an embed instead.

    The concept of the embed is that we register a ‘fake’ oembed. It’s not an endpoint, it’s just saying “Hey, WordPress. When you see this kind of URL all alone, let’s make magic.”

    It’s surprisingly straightforward. All we need to know are two things:

    1. What is the URL people are going to paste in?
    2. What is the output supposed to look like?

    Since we’ve already done this as a shortcode, we’re ready to go.

    Register the Handler

    First we have to tell it that we’re making a new handler, called indiegogo and this is the kind of URL to expect:

    wp_embed_register_handler( 'indiegogo', '#https?://www\.indiegogo\.com/projects/.*#i', 'indiegogo_embed_handler' );
    

    The first part, indiegogo, is the name. It should be unique.

    The second part, '#https?://www\.indiegogo\.com/projects/.*#i' is saying “http OR https” and “as long as the URL starts with www.indigogo.com/projects” — it’s ‘basic’ regex.

    The last bit, indiegogo_embed_handler is the function name we’re going to need.

    Write the Embed Function

    This is very similar to the shortcode. We take the data, make sure it’s formatted correctly, and output the (in this case) iFrame:

    function indiegogo_embed_handler( $matches, $attr, $url, $rawattr ) {
    	$url   = esc_url( $matches[0] );
    	$url   = rtrim( $url, "#/");
    	$url   = str_replace( 'projects/', 'project/', $url );
    	$embed = sprintf( '<iframe src="%1$s/embedded" width="222" height="445" frameborder="0" scrolling="no"></iframe>', $url );
    	return apply_filters( 'indiegogo_embed', $embed, $matches, $attr, $url, $rawattr );
    }
    

    I’ve left the filters in place in case I decide I want to do more weird things to it, without having to edit the core part of my code.

    A GutenGotcha

    For some reason, this doesn’t work in Gutenberg, and it tells me it cannot embed the content. Except when you visit the page, everything is embedded perfectly.

  • A Slightly More Complex Sample Box: Spoilers

    A Slightly More Complex Sample Box: Spoilers

    Round two!

    Once I made a simple, sample spoiler box, it was time to jump into the next stage. Customizable, editable, not simple, sample spoiler boxes!

    Here’s the best part. All I had to change was the index.js file from the previous example.

    The Javascript

    ( function( blocks, i18n, element ) {
    	var el = element.createElement;
    	var __ = i18n.__;
    	var RichText = blocks.RichText;
    
    	blocks.registerBlockType( 'library/spoilers', {
    
    		title: __( 'Spoiler Warning' ),
    		icon: 'vault',
    		category: 'widgets',
    		supportHTML: false,
    
    		attributes: {
    			content: {
    				type: 'array',
    				source: 'children',
    				selector: 'div',
    			},
    		},
    
    		edit: function( props ) {
    			var content = props.attributes.content || 'Warning: This post contains spoilers!';
    			var focus = props.focus;
    			function onChangeContent( newContent ) {
    				props.setAttributes( { content: newContent } );
    			}
    
    			return el(
    				RichText,
    				{
    					tagName: 'div',
    					className: props.className,
    					onChange: onChangeContent,
    					value: content,
    					focus: focus,
    					onFocus: props.setFocus
    				}
    			);
    		},
    
    		save: function( props ) {
    			return el(
    				'div',
    				{ className: 'alert alert-danger'},
    				props.attributes.content
    			);
    		}
    	} );
    } )(
    	window.wp.blocks,
    	window.wp.i18n,
    	window.wp.element
    );
    

    What’s Different?

    A few things. A lot of things. The idea is that we need to pass the content attribute (i.e. our warning) to be processed. This is very much like how you pass attributes through shortcodes, so don’t panic.

    var content = props.attributes.content || 'Warning: This post contains spoilers!';
    var focus = props.focus;
    function onChangeContent( newContent ) {
    	props.setAttributes( { content: newContent } );
    }
    

    This says “Set the content to ‘Warning: This post contains spoilers!’ if there’s nothing there. Then watch the focus. If the focus changes, use the new content to replace the original content.”

    Down in our return el section, we’ve changed it to be Rich Text (so people can use bold and so on… even though it’s always bold), and the value: content, is the variable content we edited above.

    What’s It Like?

    It’s just like any other Block. It inserts itself when you click the icon, it loads the default, and you can edit it:

    An example Gif of spoilers

    And that is a simple, editable, Gutenberg Block

  • A Sample Block: Spoilers

    A Sample Block: Spoilers

    Before I jump into this, I have to say .. this post was not written in Gutenberg.

    Sadly the plugin I use for code display, when I need it to be colored and easy to read, isn’t yet Gutenberg friendly. And, worse IMO, there’s a bug that causes multiline shortcodes to be smashed into one line, which makes a code block unusable. My two fixes are either the plugin I use be updated (which is beyond my skills at the moment) or I find a new plugin (looking). Or I wait.

    Anyway.

    Let’s make a simple block that you can’t edit!

    There are Four Files Needed

    1. spoilers.php – This is the main PHP file
    2. spoilers/index.js – This is the code
    3. spoilers/editor.css – This formats what you see on the editor
    4. spoilers/style.css – This formats what you see on the front end

    The last two aren’t required but I use them to make things pretty.

    The PHP

    The PHP file will need to be included in your code however you want to do it. I have a file called _blocks.php which includes all my Gutenblocks. In turn, it is included in my plugin’s main file.

    function lp_spoilers_block_init() {
    	$dir = dirname( __FILE__ );
    
    	$index_js = 'spoilers/index.js';
    	wp_register_script(
    		'spoilers-block-editor',
    		plugins_url( $index_js, __FILE__ ),
    		array( 'wp-blocks', 'wp-i18n', 'wp-element' ),
    		filemtime( "$dir/$index_js" )
    	);
    
    	$editor_css = 'spoilers/editor.css';
    	wp_register_style(
    		'spoilers-block-editor',
    		plugins_url( $editor_css, __FILE__ ),
    		array( 'wp-blocks' ),
    		filemtime( "$dir/$editor_css" )
    	);
    
    	$style_css = 'spoilers/style.css';
    	wp_register_style(
    		'spoilers-block',
    		plugins_url( $style_css, __FILE__ ),
    		array( 'wp-blocks' ),
    		filemtime( "$dir/$style_css" )
    	);
    
    	register_block_type( 'library/spoilers', array(
    		'editor_script' => 'spoilers-block-editor',
    		'editor_style'  => 'spoilers-block-editor',
    		'style'         => 'spoilers-block',
    	) );
    }
    add_action( 'init', 'lp_spoilers_block_init' );
    

    The JS

    Here’s the weird stuff. And I’m going to be honest here … I don’t understand all of this yet. But I picked this very simple example because it lets you see what’s going on in a concrete way.

    ( function( wp ) {
    	var registerBlockType = wp.blocks.registerBlockType;
    	var el = wp.element.createElement;
    	var __ = wp.i18n.__;
    
    	registerBlockType( 'library/spoilers', {
    
    		title: __( 'Spoiler Warning' ),
    		icon: 'vault',
    		category: 'widgets',
    		supportHTML: false,
    
    		edit: function( props ) {
    			return el(
    				'div',
    				{ className: props.className },
    				__( 'Warning: This post contains spoilers!' )
    			);
    		},
    
    		save: function() {
    			return el(
    				'div',
    				{ className: 'alert alert-danger'},
    				__( 'Warning: This post contains spoilers!' )
    			);
    		}
    	} );
    } )(
    	window.wp
    );
    

    The CSS

    There are two CSS files.

    editor.css

    .wp-block-library-spoilers {
    	border: 1px dotted #f00;
    	background-color: pink;
    	font-weight: bold;
    }
    

    style.css

    .wp-block-library-spoilers {
    	font-weight: bold;
    }
    

    Back in the js there was a bit that looked like this: { className: props.className },

    That’s what tells it to use these. In addition, I use this to call some theme specific code: { className: 'alert alert-danger'},

    The Output

    On the editor, I see this:

    Example of what the spoiler text looks like on the editor

    I included the block icon so you could see the little vault I used to indicate the block.

    On the front end, everyone sees this:

    A nice looking spoiler warning

    What’s Next?

    Making it editable, of course!