In my last post, I talked about relating posts to a custom post type. That is, how I listed the blog posts tagged with a show on the show page. Let’s do the reverse!

Continuing the Click Hole

While we’re very good about remembering to tag the posts we write with the shows they’re about, we’re not always as good with remembering to link the first instance of the show name to the show. That is, when we write about Supergirl we sometimes forget to link that to the page for her.

That said, we still want to make it ‘easy’ for people to figure out where they can read more about the show. The ‘simplest’ way to do that would be to have a block at the bottom of each blog post. “Want to know more about the shows in this post?” or something along those lines.

Relations Back Across Post Types

The difficulty here is that if you want to get post data based on a post name, it’s easy. There’s a handy little function get_page_by_title() where you can put in this: get_page_by_title( 'Supergirl', OBJECT, 'post_type_shows' ); where Supergirl is the name of the show and post_type_shows is the post type.

That’s well and good, but I knew there would be cases where the tag wasn’t going to match the name. People name shows pretty weird stuff (#hastag for example is the name of a show). Instead, I knew that I needed the tag slug and for that, I needed a different function: get_page_by_path()

The Code

Here’s the magic sauce:

function related_shows( $content ) {
    if ( is_singular( 'post' ) ) {
		$posttags = get_the_tags( get_the_ID() );
		$shows = '';
		if ( $posttags ) {
			foreach ( $posttags as $tag ) {
				if ( $post = get_page_by_path( $tag->name, OBJECT, 'post_type_shows' ) ) {
					$shows .= '<li><a href="/show/' . $post->name . '">'. $tag->name . '</a></li>';
				}
			}
		}
		if ( $shows !== '' ) {
			$content .= '<section class="related-shows"><div><h4 class="related-shows-title">Read more about shows mentioned in this post:</h4><ul>' . $shows . '</ul></div></section>';
		}
	}
	return $content;
}

This has a few failsafes in there, like it only runs on single posts, it has to have at least one tag, and it has to have at least one tag that’s a show. Whew.

After that, it’s just the CSS.

Reader Interactions

%d bloggers like this: